繁体   English   中英

如何在Jest中的不同测试套件中覆盖模块的模拟数据

[英]How to overwrite the mocked data for a module in different test suite in Jest

我有一个场景,我必须用Jest编写的一个单元测试用例中的一个,在不同的测试套件中更新具有不同值集的模块的模拟响应。 这是我的测试文件,看起来像:

// test.spec.js

  jest.mock('../../Service', () => ({
    getState: jest.fn().mockReturnValue({
      x: 'x',
      y: 'y',
      z: 'z' 
    })
  })

describe('Test suite 1 - with same mocked data for Service', () => ({
   // expected Service.getState() --> { x: 'x', y: 'y', z: 'z' }
})

describe('Test suite 2 - with different mocked data for Service', () => ({
 // expected Service.getState() --> { a: 'a', b: 'b' } 
})

如何在第二个测试套件中使用另一组值更新以下模块的模拟值,如下所示?

jest.mock('../../Service', () => ({ 
  getState: jest.fn().mockReturnValue ({ 
    a: 'a',
    b: 'b'
  })
})

是否可以在第二个测试套件中使用beforeEach()方法覆盖模拟值? 有人可以让我以正确的方式处理这种情况吗?

任何帮助,将不胜感激。

假设您有一个测试文件SomeComponent.jsx ,其中涉及../../Service依赖项,那么您可以执行以下操作:

import { Service } from "../../Service";

jest.mock("../../Service", ({
  getState: jest.fn(),
}));

describe("SomeComponent", () => {
  describe('Test suite 1 - with same mocked data for Service', () => {

    it('should expect mock response 1', () => {
      getState.mockImplementation(() => {
        return {
          x: 'x',
          y: 'y',
          z: 'z'
        }
      })
      expect(Service.getState()).toEqual({x: 'x', y: 'y', z: 'z'});

    });
  });

  describe('Test suite 2 - with different mocked data for Service', () => {

    it('should expect mock response 2', () => {
      getState.mockImplementation(() => {
        return {a: 'a', b: 'b'}
      })
      expect(Service.getState()).toEqual({a: 'a', b: 'b'});

    });
  });
});

您要测试getState的两个对象,因此可以使用mockReturnValueOnce使模拟函数在第一次调用中返回object1,在第二次调用中返回object2。

在这种情况下,可以import {Service} from "../../Service" 获得对模拟功能的访问。 然后,您可以使用不同的测试服在测试体内调用mockImplementation来设置正确的返回值。

 describe('Test suite 1 - with same mocked data for Service', () => ({ // expected Service.getState() --> { x: 'x', y: 'y', z: 'z' } jest.mock('../../Service', () => ({ getState: jest.fn().mockReturnValue({ x: 'x', y: 'y', z: 'z' }) }) }) describe('Test suite 2 - with different mocked data for Service', () => ({ // expected Service.getState() --> { a: 'a', b: 'b' } jest.mock('../../Service', () => ({ getState: jest.fn().mockReturnValue({ a: 'a', b: 'b', }) }) }) 

您必须在每个测试案例中分别模拟服务。 而不是全局地在describe块中。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM