javascript - 如何从 beforeEach() 传递值进行测试?摩卡/柴
问题描述
如何将dom
对象从我的 beforeEach() 函数传递给我的测试?
例如:
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
没有绑定到function
传递给的回调beforeEach
。解决方案是.bind(this)
使用箭头函数或使用范围为describe
回调块的变量。
下面是一个使用箭头函数的例子:
describe('tests', () => {
beforeEach(async () =>
Promise.resolve('foo').then(result => {
this.dom = result;
})
);
it('works', () => {
console.log(this.dom); // => foo
});
});
推荐阅读
- asp.net - 有没有办法用HttpClient获取api输入参数?
- javascript - 在 react-native 中无错误导航之前更改状态
- macos - 如果我在 MacBook Pro 上重新打开终端,则找不到 nvm
- android - 无障碍服务对事件的行为
- angular - 角路由器散列
- googleplacesautocomplete - 需要在 Google Place Autocomplete 中获取英文地名
- django - Django 使用中间件设置 cookie 在第一页加载时失败
- electron - 带有私有 GitHub 存储库的电子自动更新器?
- django - 如何将通用视图转换为具有模式列表的基于类的视图
- excel - VBA 使用子参数中的值填充不同的对象