挂钩之前未运行挂钩之前的Mocha

时间:2018-12-19 14:32:02

标签: javascript node.js mocha

我是Node和Mocha的新手,在理解Mocha为什么跳过我的“之前”挂钩代码以在以下示例中创建Json Web令牌时遇到困难:

//index.js
const createJWT = require('./lib/config/createJWT');
const expect = require('chai').expect;

before(async() => {

  const jwt = await createJWT() {
    return new Promise(
      function(resolve, reject) {
        resolve(jwt);
      }
    )
  }
  const person = createPerson(jwt);

}); //this is where the jwt is created, making it useless for createPerson

describe('My other tests', () => {
it('Customer sign up', async() => {
  const signUpText = await customerSignUp(page, frame);

  expect(signUpText).to.equal("You have signed up")

  });
 });
});

createJWT()方法如下:

 //createJWT.js
module.exports = async() => {

  const options = {
    method: 'POST',
    url: 'https://my-website.auth.io/oauth/token',
    headers: {
      'content-type': 'application/json'
    },
    body: '{"client_id":"dew76dw7e65d7w65d7wde"}'
  };

    request(options, function (error, response, body) {
    try {
        console.log(body);
        jwt = body;
        return jwt = body;
    } catch
        (error) {
    }
  });
};

当我调试时,设置代码被跳过。有什么明显的我想念的东西吗?

1 个答案:

答案 0 :(得分:2)

我很确定您需要将before钩子放入相同的测试块中,然后才能运行它。 例如:

r'\[(.{6})\]\s(.*?)\s\['

或:

before(async() => {

  const jwt = await createJWT();

});

describe('My other tests', () => {
  it('Customer sign up', async() => {
    const signUpText = await customerSignUp(page, frame);

    expect(signUpText).to.equal("You have signed up")
  });
});

此外,您的describe('My other tests', () => { before(async() => { const jwt = await createJWT(); }); it('Customer sign up', async() => { const signUpText = await customerSignUp(page, frame); expect(signUpText).to.equal("You have signed up") }); }); 方法不会返回Promise,从而阻止了等待工作。您需要执行以下操作:

createJwt