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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jestjs - Mocked async callback function is not called, the original is (Jest)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...