簡體   English   中英

如何使用 react-testing-library 在 Typescript 中測試公共功能?

[英]How to test public functions in Typescript with react-testing-library?

我的項目中有以下設置,每當我擴展 httpService 並在任何服務中使用“this.instance”時,我都會收到錯誤消息。

如果我直接使用 axios.get 而我的服務文件中沒有任何攔截器,它工作正常。

我是單元測試的新手,並且非常堅持這一點。 請在下面分享你的評論。 這真的很有幫助。

httpClient.ts

 import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
 import { DEFAULT_HEADERS, HOST } from './ApiHelper';
    
    export abstract class HttpService {
      protected readonly instance: AxiosInstance;
    
      public constructor(requestConfig: AxiosRequestConfig) {
        this.instance = axios.create(requestConfig);
    
        this.instance.interceptors.request.use((request) => {
          request.baseURL = HOST;
          request.headers = { ...DEFAULT_HEADERS };
          return request;
        });
    
        this.instance.interceptors.response.use(
          (response) =>
            response,
          (error) =>
            new Promise((resolve, reject) => {
              reject(error.response);
            }),
        );
      }
    }
    
    export default HttpService;

一些服務.ts

    import HttpService from './HttpService';
    
    const warningListUrl = 'some/url';
    
    class SomeService extends HttpService {
      public constructor() {
        super({
        });
      }
    
      public async getSomething(params: any) {
        this.instance({
          method: 'GET',
          url: warningListUrl,
          params,
        }).then((res) =>
          res.data);
      }
    }

export default SomeService;

反應組件.tsx

const fetchList = async () => {
    try {
      setIsLoading(true);
      const someService = new SomeService();
      const response: any = await someService.getSomething({});
      setWarnings(response.content);
      setTotalPages(response.totalPages);
    } catch (error) {
      console.log(error);
    } finally { setIsLoading(false); }
  };

  useEffect(() => {
    fetchList();
  }, []);

ReactComponent.test.tsx

jest.mock('../../services/SomeService');
const someService = new SomeService();


describe('page tests', () => {
  test('page renders without crashing', async () => {
    (someService.getWarningList as jest.Mock).mockResolvedValue(someMatchingData);
    await act(async () => {
      render(<ReactComponent />);
    });
    const text = screen.getByText('Warning 1');
    expect(text).toBeInTheDocument();
  });
}

錯誤:

TestingLibraryElementError: Unable to find an element with the text: Warning 1. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

render(<Warning />);
});
-> const text = screen.getByText('Warning 1');
 expect(text).toBeInTheDocument();
});

如果您只需要模擬特定方法,則可以使用requireActual

jest.mock('../../services/SomeService', ()=> {
  return {
    ...jest.requireActual('../../services/SomeService'),
    getWarningList: new Promise.resolve(someMatchingData)
  }
})

像這樣模擬一個模塊怎么樣?

通過“原型”訪問方法節省了我的時間。

(someService.prototype.getWarningList as jest.Mock).mockResolvedValue(someMatchingData);

只需在測試描述上方添加它就救了我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM