简体   繁体   English

在 function 中使用 Jest 测试 promise 的结果

[英]Testing the result of a promise with Jest inside a function

The jest documentation cover the case where a given function return a Promise and demonstrate how to test it. jest文档涵盖了给定 function 返回 Promise 的情况,并演示了如何测试它。
But how do I test a void function calling the .then of a Promise inside the function?但是我如何测试 void function 在 function 中调用.then的 .then?

Here is an example on how I was thinking about doing it nevertheless this is not working.这是一个示例,说明我是如何考虑这样做的,但是这是行不通的。

The function function

function dummyFunction(): void {
   dummyService.getDummy$().then((dummy: Dummy): void => {
      console.log(`Dummy fetched`);
   });
}

The tests测试

describe(`dummyFunction()`, (): void => {
   let dummyServiceGetDummy$Spy: jest.SpyInstance;
   let consoleLogSpy: jest.SpyInstance;

   beforeEach((): void => {
      dummyServiceGetDummy$Spy = jest.spyOn(dummyService, `getDummy$`).mockImplementation();
      consoleLogSpy = jest.spyOn(console, `log`).mockImplementation();
   });

   it(`should fetch dummy`, (): void => {
      expect.assertions(2);

      dummyFunction();

      expect(dummyServiceGetDummy$Spy).toHaveBeenCalledTimes(1);
      expect(dummyServiceGetDummy$Spy).toHaveBeenCalledWith();
   });

   describe(`when dummy was successfully fetched`, (): void => {
      beforeEach((): void => {
         dummyServiceGetDummy$Spy.mockReturnValue((): Promise<void> => Promise.resolve());
      });

      it(`should log`, (): void => {
         expect.assertions(2);

         dummyFunction();

         expect(consoleLogSpy).toHaveBeenCalledTimes(1);
         expect(consoleLogSpy).toHaveBeenCalledWith(`Dummy fetched`);
      });
   });
});

Dependencies依赖关系

"jest": "26.0.1"
"ts-jest": "26.0.0"

Promise encapsulation is an antipattern. Promise 封装是一种反模式。 dummyFunction should return a promise to chain in order to be properly reused and tested: dummyFunction应该将 promise 返回到链中以便正确重用和测试:

function dummyFunction(): void {
   return dummyService.getDummy$().then((dummy: Dummy): void => {
      console.log(`Dummy fetched`);
   });
}

Then it can be tested with built-in Jest promise support:然后可以使用内置的 Jest promise 支持进行测试:

   it(`should fetch dummy`, async () => {
      await expect(dummyFunction()).resolves.toBe(undefined);

      expect(dummyServiceGetDummy$Spy).toHaveBeenCalledWith();
      expect(consoleLogSpy).toHaveBeenCalledWith(`Dummy fetched`);
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM