【问题标题】:How do I pass value from beforeEach() to test? Mocha/Chai如何从 beforeEach() 传递值进行测试?摩卡/柴
【发布时间】:2019-11-10 01:26:53
【问题描述】:

如何将 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;
 })
});

【问题讨论】:

    标签: javascript mocha.js tdd chai


    【解决方案1】:

    问题在于this 未绑定到传递给beforeEach 的回调function。解决方案是.bind(this),使用箭头函数或使用范围为describe 回调块的变量。

    这是一个使用箭头函数的例子:

    describe('tests', () => {
      beforeEach(async () =>
        Promise.resolve('foo').then(result => {
          this.dom = result;
        })
      );
    
      it('works', () => {
        console.log(this.dom); // => foo
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多