TheBrainFamily / wait-for-expect

Wait for expectation to be true, useful for integration and end to end testing. Integral part of react-testing-library.
MIT License
293 stars 31 forks source link

Async await usages not showing expectation library error #32

Open sekhavati opened 3 years ago

sekhavati commented 3 years ago

Early on in the README it mentions:

Nice thing about this simple tool is that if the expectation keeps failing till the timeout, it will check it one last time, but this time the same way your test runner would run it - so you basically get your expectation library error

For example:

 FAIL  src/waitForExpect.spec.js (5.042s)
  ✕ it waits for the number to change (4511ms)

  ● it waits for the number to change

    expect(received).toEqual(expected)

    Expected value to equal:
      105
    Received:
      100

       9 |   }, 600);
      10 |   await waitForExpect(() => {
    > 11 |     expect(numberToChange).toEqual(105);
      12 |   });
      13 | });
      14 | 

      at waitForExpect (src/waitForExpect.spec.js:11:28)
      at waitUntil.catch (src/index.js:61:5)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        5.807s

But when I have an async/await scenario I no longer get this nice print out highlighting the line where the expectation didn't hold true, instead I get a Jest timeout error. Tweaking your own async example from the docs I get this:

const waitForExpect = require("wait-for-expect");

test("it works with promises", async () => {
  let numberToChange = 10;
  const randomTimeout = Math.floor(Math.random() * 300);

  setTimeout(() => {
    numberToChange = 100;
  }, randomTimeout);

  const sleep = (ms) =>
    new Promise((resolve) => setTimeout(() => resolve(), ms));

  await waitForExpect(async () => {
    await sleep(10);
    expect(numberToChange).toEqual(200); // <--  deliberately cause it to fail
  });
});

Result:

Exceeded timeout of 5000ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.

Am I doing something wrong, is this expected behaviour or is it a bug? (I was testing with version 3.0.2)

sekhavati commented 3 years ago

@lgandecki would you be able to comment on the above please? I'm keen to understand if I'm doing something daft or whether trying to fix this on my end is futile

lgandecki commented 3 years ago

Sorry for that. I'm guessing the timeout is somehow exceeded, does it change anything if you change your timeout default like so:

waitForExpect.defaults.timeout = 1000;

meetwudi commented 3 years ago

Having the same issue and no, the above remediation does not resolve it.

lgandecki commented 3 years ago

Sorry for the troubles :-( Do you guys have any simple repo that you could push to github that I could clone and reproduce? I'm loaded with work but if someone could help with the first step I might be able to figure out the problem much quicker.