我正在try 使用JEST模拟一个对象来测试一些实现,每个测试用例都可以覆盖JEST.请让我知道,如果你已经解决了类似的问题或任何其他更好的解决方案来模拟一个对象使用JEST.

import {obj} from "./filepath/obj";

jest.mock("./filepath/obj", () => ({
  obj:{
    search: jest.fn(),
    items:[1,2,3]
  }

}))

test("test 1", () => {
  expect(obj.items.length).toBe(3); // works
})

// now if I try to override, for some other test case that doesn't work
test("test 1", () => {
  jest.mock("./filepath/obj", () => ({
    obj:{
      search: jest.fn(),
      items:[]
    }

  }))
   
  expect(obj.items.length).toBe(0); // doesn't work
})

我们如何覆盖可以在每个测试用例中工作的对象的模拟实现?

更多上下文:该对象是从我们拥有store 定义的文件中导出的mobxstore 对象.然后,我们通过导入在组件中使用该存储对象.现在,在测试组件时,我们try 如上所述模拟store 对象.

推荐答案

不需要将factory参数传递给jest.mock(),只需让JEST在需要时使用自动模拟版本模拟模块即可.

这意味着obj.items将被替换为空数组[],原始的obj.search()方法将被替换为jest.fn().您可以通过赋值来更改每个测试用例中obj.items属性值.

例如.

obj.js:

const obj = {
    search: () => 'real implementation',
    items: [0, 0, 0],
};

export { obj };

index.test.js:

import { obj } from './obj';

jest.mock('./obj');

describe('76570418', () => {
    test('should pass 0', () => {
        expect(obj.items).toHaveLength(0);
        expect(jest.isMockFunction(obj.search)).toBeTrue();
    });
    test('should pass 1', () => {
        obj.items = [1, 2, 3];
        expect(obj.items).toHaveLength(3);
        expect(jest.isMockFunction(obj.search)).toBeTrue();
    });
    test('should pass 2', () => {
        obj.items = [];
        expect(obj.items).toHaveLength(0);
        expect(jest.isMockFunction(obj.search)).toBeTrue();
    });
    test('should pass 3', () => {
        Object.assign(obj, { items: [1], a: 1 });
        expect(obj.items).toHaveLength(1);
        expect(obj.a).toBe(1);
        expect(jest.isMockFunction(obj.search)).toBeTrue();
    });
});

测试结果:

 PASS  stackoverflow/76570418/index.test.js (7.347 s)
  76570418
    ✓ should pass 0 (1 ms)
    ✓ should pass 1 (1 ms)
    ✓ should pass 2
    ✓ should pass 3 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        7.616 s

Reactjs相关问答推荐

无法使用#13;或br将新行设置为文本区域'"&"<>

包装组件可以避免子组件重新渲染.?

REACTJS:在Reaction中根据路由路径更改加载器API URL

有没有一种惯用的方式来接受特定的子元素?

React:关于useEffect钩子如何工作的困惑

在React中映射对象数组时,如何正确呈现JSX.Element或React.ReactNode类型?

在react上隐藏源映射

tRPC/react-query,在所有查询完成之前,组件不会收到任何 useQuery 的结果

Symfony ux-react:使用react_component()时React组件不会渲染

强制 useEffect 仅运行一次

如何在不使用 Axios 的情况下将图像文件从 React.js 发送到 Spring Boot Rest API?

React - 错误边界未捕获错误

使用带有搜索字符串的全局过滤器时如何在 React-Table 中进行精确匹配?

使用 react-markdown 组件时 Tailwind CSS 的问题

如何在同一路由路径上重新渲染组件(链接,V6)reactjs

antd 找不到 comments

渲染的钩子比预期的少.这可能是由 React Hooks 中意外的提前返回语句引起的

如何定制 React 热 toastr ?

如何在 React JS 上使文本中的单词可点击

将 set statehook 函数传递给子路由组件.解构错误