How do I pass value from beforeEach() to test? Mocha/Chai

孤街醉人 提交于 2021-02-11 02:49:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!