javascript - Hook 之前的 Mocha 在套件之前没有运行

标签 javascript node.js mocha.js

我是 Node 和 Mocha 的新手,我很难理解为什么 Mocha 在以下示例中跳过我的“之前” Hook 代码来创建 Json Web token :

//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) {
    }
  });
};

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

最佳答案

我很确定您需要将 before Hook 放在同一个测试 block 中,以便在处理之前运行它。 例如:

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")
  });
});

此外,您的 createJwt 方法不会返回 Promise,这会阻止 await 工作。你需要做这样的事情:

module.exports = async() => {

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

  return new Promise((resolve, reject) => request(options, function (error, response, body) {
    if(error) {
      reject(error);
    }
    resolve(body);
  }));
};

关于javascript - Hook 之前的 Mocha 在套件之前没有运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53853370/

相关文章:

node.js - Node.js-Ejs-Mongojs 堆栈上的 "has no method ' forEach ' TypeError"

javascript - 无法解析 Mocha 中的路径

javascript - enzyme 和 Mocha 给我 Istanbul 尔覆盖测试的错误,为什么?

javascript - 解析 Angular 5 期间的 Http 失败

javascript - JS中如何判断是否设置了多维数组项?

node.js - 邮戳模板 : dynamic variable with html processed as text instead of html

xml - Mocha Istanbul 尔覆盖 xml 文件生成

javascript - react-native-svg 中 <Rect/> 的动画宽度

javascript - 淡入淡出背景图像

php - Redis 多个连接以 TIME_WAIT 状态打开