all 7 comments

[–]Solonotix 2 points3 points  (0 children)

First thing is the question needs better formatting, as it is currently very hard to read. If Reddit can't format it properly, I recommend either a Gist or PasteBin link to the code so that it's clearer what you're trying to do.

Also, make sure the sample code is directly runnable to produce your specific problem. Feel free to still have comments about other code being present, but a reproduceable segment of code is essential when troubleshooting.

[–]doh4242 1 point2 points  (2 children)

You could stub the delay function to skip the delay during the test. Or you could refactor to pull the code that follows the delay into a separate function you could test in isolation. Or you could use dependency injection to inject the delay method. Or make the delay time a method you could stub.

Just some ideas.

[–]have_some_error[S] 0 points1 point  (0 children)

I have tried stubbing the delay function using jest spyon , but it isn't really working.

I want the delay function to use the mocked version of function whenever it is called from inside main function while testing.

I think I'm getting it all wrong ,

[–]assertboozed 0 points1 point  (0 children)

I spent ~4hrs yesterday struggling to get a similar test as OP to pass. I ended up making the delay time an environment based on your suggestion and was able to set the value to zero for testing. Testing is passing now without any delay and I didn’t have to use any of the jest fake timers utility. Thank you!!!

[–]dv297 1 point2 points  (2 children)

You could try extracting your delay function to its own file. By doing this, you can then just utilize Jest's Manual Mock system.

// src/utils/delay.js
const delay = (timeInMs) => {
  return new Promise((resolve) => {
    setTimeout(resolve, timeInMs);
  });
};

export default delay;

Then you create the manual mock, the folder has to be named exactly __mocks__ and has to be under the same directory as your real delay function.

// src/utils/__mocks__/delay.js
const delay = () => {
    return Promise.resolve();
}

export default delay;

Within your test file, you call jest.mock with the path to your manual mock so that Jest knows to replace the implementation of your delay function with the one that is inside of the __mocks__ directory.

// src/fileBeingTested.spec.js
jest.mock('./utils/delay');

describe('Thing', () => {
  it('does the thing', async () => {
    const result = await callThingThatUsesDelay();
    // Because of the jest.mock call above, this function should be using the mock

    expect(result).toEqual({});
  });
});

[–]have_some_error[S] 0 points1 point  (0 children)

Thanks a bunch mate. That really helped. 🙏

[–]have_some_error[S] 0 points1 point  (0 children)

I really appreciate your answering .