简体   繁体   English

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

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

I'm having below setup in my project, whenever I extends the httpService and use the 'this.instance' in any service I'm getting the error.我的项目中有以下设置,每当我扩展 httpService 并在任何服务中使用“this.instance”时,我都会收到错误消息。

If I use axios.get directly without any interceptors in my service files its working fine.如果我直接使用 axios.get 而我的服务文件中没有任何拦截器,它工作正常。

Im new to the unit testing and badly stuck with this.我是单元测试的新手,并且非常坚持这一点。 Please share your comments below.请在下面分享你的评论。 It'll be really helpful.这真的很有帮助。

httpClient.ts 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;

someService.ts一些服务.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;

ReactComponent.tsx反应组件.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 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();
  });
}

Error:错误:

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();
});

You could use requireActual if you need to mock only specific methods.如果您只需要模拟特定方法,则可以使用requireActual

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

How about mocking a module like this?像这样模拟一个模块怎么样?

Accessing methods through 'prototype' saved my day.通过“原型”访问方法节省了我的时间。

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

just adding it above the test description saved me.只需在测试描述上方添加它就救了我。

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

相关问题 如何使用jest和react-testing-library测试上下文提供的功能? - How can I test functions that are provided by context using jest and react-testing-library? 如何使用 Jest 和 react-testing-library 测试 react-dropzone? - How to test react-dropzone with Jest and react-testing-library? 如何使用 react-testing-library 测试 react-select - how to test react-select with react-testing-library 如何用 jest 和 react-testing-library 测试 react-toastify - How to test react-toastify with jest and react-testing-library 如何在反应测试库中测试父子关系? - How to test parent child relationship in react-testing-library? 如何使用 Jest 和 React-Testing-Library 模拟和测试 scrollBy? - How to mock and test scrollBy with Jest and React-Testing-Library? 如何使用 react-testing-library 测试锚的 href - How to test anchor's href with react-testing-library 如何使用 react-testing-library 和 jest 测试链接 - How to test link using react-testing-library and jest 如何测试用 div(react-testing-library)渲染的组件数量? - How to test the number of components that are rendered with a div (react-testing-library)? 如何使用 react-testing-library 测试带有动作重定向的表单 - How to test a form with action redirection using react-testing-library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM