[英]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.