如何在jest中将mocked函数还原为原始值?

q8l4jmvw  于 2023-09-28  发布在  Jest
关注(0)|答案(3)|浏览(141)

我在一个测试中模拟了一个类的静态函数,但我会影响其他测试。由于静态函数的性质,代码为:

test('A', async () => {
    expect.assertions(2);
    let mockRemoveInstance = jest.fn(() => true);
    let mockGetInstance = jest.fn(() => true);
    User.removeInstance = mockRemoveInstance;
    User.getInstance = mockGetInstance;
    await User.getNewInstance();
    expect(mockRemoveInstance).toHaveBeenCalled();
    expect(mockGetInstance).toHaveBeenCalled();
  });

  test('B', () => {
    let mockRemoveInstance = jest.fn();
    const Singletonizer = require('../utilities/Singletonizer');
    Singletonizer.removeInstance = mockRemoveInstance;
    User.removeInstance();
    expect.hasAssertions();
    expect(mockRemoveInstance).toHaveBeenCalled();
  });

B测试中,User.removeInstance()仍然被A测试所模仿,如何将removeInstance()重置为由其类定义的原始函数?

gg58donl

gg58donl1#

你可以尝试使用jest.spyOn
这样的东西应该会为你恢复功能:-

let mockRemoveInstance = jest.spyOn(User,"removeInstance");
    mockRemoveInstance.mockImplementation(() => true);

    User.removeInstance();
    expect(mockRemoveInstance).toHaveBeenCalledTimes(1);

    // After this restore removeInstance to it's original function

    mockRemoveInstance.mockRestore();
pgky5nke

pgky5nke2#

我有一个类似的问题,我必须模拟一个外部函数进行一个测试,但Jest不会/无法恢复函数的原始值。
所以我最后用了这个,但我很想知道是否有更好的方法

it('should restore the mocked function', async () => {
      const copyOfFunctionToBeMocked = someClass.functionToBeMocked;
      someClass.functionToBeMocked = jest.fn().mockReturnValueOnce(false);

      // someClass.functionToBeMocked gets called in the following request
      const res = await supertest(app)
        .post('/auth/register')
        .send({ email: '[email protected] });

      // Not ideal but mockReset and mockRestore only reset the mocked function, NOT to its original state
      someClass.functionToBeMocked = copyOfFunctionToBeMocked;

      expect(...).toBe(...);
    });

不雅,但它的工作;

vsaztqbk

vsaztqbk3#

在Vue JS中,我做了以下事情:

// mock **myFunctionName**
 wrapper.vm.myFunctionName = jest.fn()

 wrapper.vm.somOtherFunction()

 expect(wrapper.vm.myFunctionName).toHaveBeenCalled()

// Remove mock from **myFunctionName**
 wrapper.vm.myFunctionName.mockRestore()

相关问题