在Jest中测试承诺的最佳方法

Amb*_*tle 13 javascript jestjs

除非我误解了某些内容,否则在vNext之前,解析和拒绝(https://facebook.github.io/jest/docs/expect.html#resolves)将无法使用.现在/同时用Jest测试承诺的推荐方法是什么?它只是把期望放在天堂和渔获物中吗?

例如:

describe('Fetching', () => {
    const filters = {
        startDate: '2015-09-01'
    };
    const api = new TestApiTransport();

    it('should reject if no startdate is given', () => {
        MyService.fetch().catch(e => expect(e).toBeTruthy()); // see rejects/resolves in v20+
    });            

    it('should return expected data', () => {
        MyService.fetch(filters, null, api).then(serviceObjects => {
            expect(serviceObjects).toHaveLength(2);
        }).catch(e => console.log(e));
    });            
});
Run Code Online (Sandbox Code Playgroud)

Yev*_*huk 17

现在你也可以用这种方式写它:docs

describe('Fetching', () => {
    const filters = {
        startDate: '2015-09-01'
    };
    const api = new TestApiTransport(); 

 it('should reject if no startdate is given', () => {
   expect.assertions(1);
   return expect(MyService.fetch()).rejects.toEqual({
     error: 'Your code message',
   });
 });          


 it('should return expected data', () => {
   expect.assertions(1);
   return expect(MyService.fetch(filters, null, api)).resolves.toEqual(extectedObjectFromApi);
 });            
});
Run Code Online (Sandbox Code Playgroud)

更新(06.01.2019)

同意接受的答案不能正常工作,因为线路 expect.assertions(1);完成了所有的魔力.链接到文档

expect.assertions(number)验证在测试期间是否调用了一定数量的断言.这在测试异步代码时通常很有用,以确保实际调用回调中的断言.

因此,将此行放在顶部将控制在运行测试时产生的特定断言.


And*_*rle 12

要么返回一个承诺,要么期望在resolvecatch

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);
      })
  });
});
Run Code Online (Sandbox Code Playgroud)

或使用 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);
  });
});
Run Code Online (Sandbox Code Playgroud)