首页 > 解决方案 > 如何从 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;
 })
});

标签: javascriptmocha.jstddchai

解决方案


问题是它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
  });
});

推荐阅读