如何在玩笑中将模拟函数恢复为原始值? [英] how to revert mocked function to original value in jest?

查看:33
本文介绍了如何在玩笑中将模拟函数恢复为原始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I mock a static function of a class in a test but i will effect on other test. because of nature of static function, the code is:

  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() 到其类定义的原始函数中?

In B test User.removeInstance() still is mocked by A test, how could reset the removeInstance() in to the original function that is defined by its class?

推荐答案

您可以尝试使用 jest.spyOn

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

Something like this should restore the function for you:-

    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();

这篇关于如何在玩笑中将模拟函数恢复为原始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆