问题
How do I pass the dom
object, from my beforeEach() function, to my tests?
For example:
describe('2) Key DOM elements exist', function() {
beforeEach(function(done){
JSDOM.fromURL('http://localhost:3000/', ).then(dom => {
this.hello = dom;
});
done();
});
it('a) Header element is present', function() {
console.log(hello);
const header = dom.window.document.getElementById('header');
expect(header).to.exist;
})
});
回答1:
The issue is that this
is not bound to the callback function
passed to beforeEach
. The solution is to .bind(this)
, use an arrow function or use a variable scoped to the describe
callback block.
Here's an example using an arrow function:
describe('tests', () => {
beforeEach(async () =>
Promise.resolve('foo').then(result => {
this.dom = result;
})
);
it('works', () => {
console.log(this.dom); // => foo
});
});
来源:https://stackoverflow.com/questions/58785033/how-do-i-pass-value-from-beforeeach-to-test-mocha-chai