Mocha Chai Sequelize:我不能使测试失败

问题描述 投票:0回答:1

我正在尝试为序列化模型编写测试,但我不明白为什么它不会失败

it('should find user by id', (done) => {
  users.findByPk(2)
  .then((retrievedUser) => {
    expect(retrievedUser.dataValues).to.deep.equal('it should break');
    done();
  })
  .catch((err) => {
    console.log(`something went wrong [should find user by id] ${err}`);
    done();
  })
});

当我运行测试时,输出如下

something went wrong [should find user by id] AssertionError: expected { Object (id, email, ...) } to deeply equal 'it should break'
1   -__,------,
0   -__|  /\_/\
0   -_~|_( ^ .^)
    -_ ""  ""

  1 passing (40ms)

如果有人想看完整的代码,我创建了一个project

mocha sequelize.js chai
1个回答
0
投票

要使异步Mocha测试失败,请将错误作为参数传递给完成的回调函数

it('should find user by id', (done) => {
  users.findByPk(2)
  .then((retrievedUser) => {
    expect(retrievedUser.dataValues).to.deep.equal('it should break');
    done();
  })
  .catch((err) => {
    console.log(`something went wrong [should find user by id] ${err}`);
    done(err);
  })
});

或者,使用不带回调的异步函数:

it('should find user by id', async () => {
  const retrievedUser = await users.findByPk(2);
  try {
    expect(retrievedUser.dataValues).to.deep.equal('it should break');
  } catch (err) {
    console.log(`something went wrong [should find user by id] ${err}`);
    throw err;
  }
});

就是说,我不建议记录测试失败的错误消息,因为这是Mocha在典型设置中已经为您完成的工作。因此,在上面的示例中,我将摆脱try-catch块。

it('should find user by id', async () => {
  const retrievedUser = await users.findByPk(2);
  expect(retrievedUser.dataValues).to.deep.equal('it should break');
});
© www.soinside.com 2019 - 2024. All rights reserved.