Home > Software design >  Jest - Test is successful even though it should not be
Jest - Test is successful even though it should not be

Time:10-13

I've simplified my scripts to let you easily understand what's going on. I have a test that waits for an object to be ready before checking whether an array contains a value.

const list = ['A', 'B', 'C'];
describe('check array', (done) => {
  it('should not contain D', () => {
    const monitor = new Monitor();

    monitor.ready().then(() => {
      expect(list.indexOf('D')).toEqual(1);

      done();
    });
  });
});

As you can see, D is not an element of list (so indexOf should return -1), but this test still passes. I've tried both toEqual and toBe with no luck. I'm wondering if it has something to do with the fact that I'm waiting for the Promise to resolve first? Thanks!

CodePudding user response:

You need to await your monitor.ready(), something like this:

const list = ['A', 'B', 'C'];

describe('check array', (done) => {
  // made function async
  it('should not contain D', async () => {
    const monitor = new Monitor();

    // wait until this call finished before continuing
    await monitor.ready();
    
    expect(list.indexOf('D')).toEqual(1);

    // not sure where this is from or what it's for
    // I assume it's defined somewhere else in your code
    done(); 
  });
});

Without doing the async/await, the test finished without a failed assertion or an error which Jest interprets as a passing test because the code in the .then(() => {...}) doesn't run until AFTER the test has been marked successful

  • Related