获得Jest中“ throw Error”的测试范围

时间:2020-10-07 16:50:26

标签: typescript unit-testing jestjs fetch

我遇到了一个问题,其中我在模拟获取端点并不断抛出错误无法覆盖的错误。测试通过了,但是如果响应无效,我该如何解决覆盖问题?

enter image description here

Test.js:

    import {RestService} from '@/services/RestService.ts';
    import 'isomorphic-fetch';
    const globalAny: any = global;
    
    describe('RestService', () => {
        jest.mock('@/config/environment', () => {
            return jest.fn(() => 'https://demo.com/');
        });
    
            const response = new Response();
    
    it('should get getAttributeDistinctValues(sucess)', async () => {
            const spy = jest.spyOn(window, 'fetch').mockImplementation(() => Promise.resolve(new Response(JSON.stringify(response))));
            const mockObject = {namespaceId: 136, attributeId: 656};
            await RestService.getAttributeDistinctValues(mockObject)
            expect(spy).toHaveBeenCalled()  
    });

    it('should get getAttributeDistinctValues(error)', async () => {
        const spy = jest.spyOn(window, 'fetch').mockImplementation(() => Promise.resolve(new Response(JSON.stringify(response))));
        const mockObject = {namespaceId: 123, attributeId: 123}; // <----Invalid
        await RestService.getAttributeDistinctValues(mockObject)
        expect(spy).toHaveBeenCalled()  
});
    
    ...

RestService.ts

class RestService {

  public static handleErrors(response: any) {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response;
  }

  public headers: any = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };

  private contextPath: string = '/auto';

  constructor() {
    this.headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };
  }

  public getAttributeDistinctValues(filters: object) {
    return this.post(`/values`, filters);
  }

    private post(url, body) {
      return fetch(`${this.contextPath}${url}`,
        { method: 'POST', headers: this.headers, body: JSON.stringify(body) })
        .then(RestService.handleErrors)
        .then((response) => response.json())
        .catch((err) => {
          throw err;
        });
    }

0 个答案:

没有答案