reactjs - 用于脚本加载的模拟实用程序函数

标签 reactjs unit-testing jestjs mocking

为简单起见,我在 stackblitz 中创建了一个示例应用程序.
Hello 组件使用了一个实用程序函数,我需要模拟该函数来测试它。

const hmmm = mockMe();

const Hello = () => (
  <div>
    <h1>Hello StackBlitz!</h1>
    <p>{hmmm}</p>
  </div>
);
我尝试了几种方法来模拟该函数,例如:
import * as utils from '../utils';

describe('Hello component', () => {
    it('should mock the utility function', () => {
        jest.spyOn(utils , 'mockMe').mockReturnValue("Mocked!");
        // render the component and test it
    }
}

我的问题是 Hello.js 在测试文件之前运行。因此,它在应用模拟之前执行实用程序函数。
我能想到的唯一解决方案是更改组件代码并将调用移动到渲染函数内的实用程序。我想避免这种变化。
有没有办法模拟效用函数并保持代码不变?

最佳答案

在使用 utils 中的方法之前你需要模拟 utils文件夹。例如,jest.mock('../utils');

关于reactjs - 用于脚本加载的模拟实用程序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64400604/

相关文章:

java - 使用 MockMVC 测试 Spring RESTful put 方法失败

javascript - 用 map 打印 react 组件内的数字?

php - 从 MySQL 检索数据到 React Native 时获取速度缓慢

scala - Play 2 框架中的单元测试 Controller 与 Scala

javascript - Expect(x).toMatchSnapshot() -> 使用默认序列化程序或 JSON.stringify()?

javascript - 使用 Jest 的 test.each 参数化测试变量作用域

javascript - 模拟 vue 组件依赖

javascript - 在 React 中过滤表格的最佳方式

javascript - 如何在 ReactJS 中为 Owl-carousel 显示加载骨架/闪光效果

swift - 测试时未找到 Google/Analytics.h 文件