用笑话测试。测试何时应该抛出

时间:2020-10-06 17:37:50

标签: javascript testing jestjs

所以我有一个带有选择方法的类,该方法带有ID并返回Promise。我想用Jest测试它,如果没有将参数传递给select(),我期望测试失败。

希望你们中的一些人可以引导我走上一条好的道路,这样我就可以解决这个问题。

预期的行为:如果未通过ID,则抛出测试

实际行为:测试失败并显示以下结果

终端

Running tests for class DB › SELECT() method tests will follow › Throws if ID is not passed

expect(received).resolves.toEqual()

Received promise rejected instead of resolved
Rejected to value: [TypeError: Cannot read property 'id' of undefined]

  35 |     it("Should resolve if data.id is not passed", () => {
  36 |       const newDB = new DB();
> 37 |       expect(newDB.insert()).resolves.toEqual({});
     |       ^
  38 |     });    

  at expect (node_modules/expect/build/index.js:134:15)
  at Object.<anonymous> (05/DB.test.js:37:7)

database.js

export default class DB {
constructor() {
    this._rows = [];
}
select(id) {
    return new Promise((resolve, reject) => {
        this.async(() => {
            const [row = null] = this._rows.filter(item => item.id === id);
            if(row) {
                resolve(row);
            } else {
                reject('ID not found');
            }
        });
    });
}

async(callback, ...params) {
    setTimeout(() => {
        callback(...params);
    }, Math.random() * 100);
}}

database.test.js

it("Throws if ID is not passed", async () => {

  const dataBase = new DB();
  expect.assertions(1);
  // return dataBase.select().catch(e => expect(e).toThrow()); <--- doesn't work either
  await expect(dataBase.select()).rejects.toThrow('error');
});

0 个答案:

没有答案