Best Way to Test Promises in Jest

后端 未结 3 946
一向
一向 2020-12-11 00:32

Unless I\'m misunderstanding something, the resolves and rejects (https://facebook.github.io/jest/docs/expect.html#resolves) won\'t be available until vNext. What is the rec

3条回答
  •  半阙折子戏
    2020-12-11 00:59

    Either return a promise and expect in the resolve or catch

    describe('Fetching', () = > {
      const filters = {
        startDate: '2015-09-01'
      };
      const api = new TestApiTransport();
      it('should reject if no startdate is given', () = > {
        return MyService.fetch()
          .catch (e => expect(e).toBeTruthy()); // see rejects/resolves in v20+
      });
      it('should return expected data', () = > {
        return MyService.fetch(filters, null, api)
          .then(serviceObjects => {
            expect(serviceObjects).toHaveLength(2);
          })
      });
    });
    

    or using async/await

    describe('Fetching', () = > {
      const filters = {
        startDate: '2015-09-01'
      };
      const api = new TestApiTransport();
      it('should reject if no startdate is given', async() = > {
        try {
          const r = await MyService.fetch()
        } catch (e) {
          expect(e).toBeTruthy()
        }
      });
      it('should return expected data', async() = > {
        const serviceObjects = await MyService.fetch(filters, null, api)
        expect(serviceObjects).toHaveLength(2);
      });
    });
    

提交回复
热议问题