如何在模仿中将模拟函数恢复为原始值?

时间:2018-03-10 13:43:55

标签: unit-testing jest

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

  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()重置为由其类定义的原始函数?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用def convert_word(): v = 0 eng = "" pig = "" movetoend = "" vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] eng = input("input english: ") listeng = eng.split() for word in listeng: if word[0] in vowels: if v == 0: for l in word: if l in vowels: movetoend = movetoend + l else: v += 1 pig += l pig = pig + movetoend + "ay" else: length = len(eng) pig = eng[1:length] + "ay" print("pig latin is: " + pig) print("program closed") convert_word()

这样的事情应该为你恢复功能: -

jest.spyOn

答案 1 :(得分:1)

我有一个类似的问题,我必须为一个测试模拟一个外部函数,但是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: 'abc@def.com });

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

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

优雅但有效;