Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I struggle testing a callback function with Jest.

Here is the function, simplified, taken from a NestJS project:

const callback = async data => this.service.patchSomething(id);
return this.client.watchSomething(id, callback);

What's wrong

I mocked both function (this.client.watchSomething and this.service.pathSomething). Both functions returns a promise.

  • this.client.watchSomething mocked function is called.
  • this.service.patchSomething mocked function is not called.
  • this.service.patchSomething original function is called and then fails the test by throwing an error.

Testing

I tried many ways but here is the actual one:

it('should do the thing', async (done) => {
      service.patchSomething = jest.fn().mockImplementation(
        async (): Promise<void> =>
          new Promise((resolve) => {
            done();
            resolve();
          }),
      );
      const serviceSpy = jest.spyOn(service, 'patchSomething');

      const clientSpy = jest.spyOn(client, 'watchSomething').mockImplementation(
        async (id, callback) => {
          await callback(null);

          return new Promise(async (resolve) => {
            resolve();
          });
        },
      );

      await theFunctionImTryingToTest('fakeId');

      expect(serviceSpy).toHaveBeenCalled();
});

Tests on clientSpy works great, I can check if the function have been called and everything.

Conclusion

Do you see what's wrong?

I'm discovering Jest and I would greatly appreciate your help. ??

question from:https://stackoverflow.com/questions/65916651/mocked-async-callback-function-is-not-called-the-original-is-jest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...