mardi 6 octobre 2020

Testing with Jest. Test fails when it should throw

So I have this class with select method that takes ID and returns a Promise. I want to test it with Jest and I am expecting the test to fail if there is no parameter passed into select().

Hopefully some of you can direct me onto good path so I can solve that problem.

Expected behaviour: test Throws if ID is not passed

Actual behaviour: test fails with following result

terminal

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 |     });    
  39 |     
  40 |     it("Should resolve if ID is a number", () => {

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

Aucun commentaire:

Enregistrer un commentaire