如何在react中使用Jest模拟单元函数



我有下面的代码在我的渲染方法

render() {
let isNew = Boolean(domService.getQueryParamByName("isNew"));
if(isNew) {
return(
// soemthing
)} else {
return(// return anything)

现在如何模拟jestUnit测试用例中的getQueryParamByName单元函数,以便它应该覆盖if块。

如果您要从另一个文件导入domService到您的组件中,那么您可以在测试中添加这样一个spy:

//component.test.js
import domService from "relative-path";
const mockFunction = jest.fn((obj) => {});
beforeEach(() => {
mockFunction.mockClear();
jest.spyOn(domService,"getQueryParamByName").mockReturnValue(mockFunction);
});

最新更新