如何从beforeEach()中传递值进行测试?摩卡/柴 [英] How do I pass value from beforeEach() to test? Mocha/Chai
本文介绍了如何从beforeEach()中传递值进行测试?摩卡/柴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 dom
对象从我的beforeEach()函数传递到测试中?
How do I pass the dom
object, from my beforeEach() function, to my tests?
例如:
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;
})
});
推荐答案
问题是 this
未绑定到传递给 beforeEach
.解决方案是使用 .bind(this)
,使用箭头函数或使用作用域为 describe
回调块的变量.
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
});
});
这篇关于如何从beforeEach()中传递值进行测试?摩卡/柴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文