首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Jest中resetAllMocks、resetModules、resetModuleRegistry、restoreAllMocks的区别

Jest中resetAllMocks、resetModules、resetModuleRegistry、restoreAllMocks的区别
EN

Stack Overflow用户
提问于 2019-09-29 07:21:31
回答 1查看 25.1K关注 0票数 61

我试着用笑话把我的大脑围绕在以下几点上:resetAllMocksresetModulesresetModuleRegistryrestoreAllMocks

我发现这很难。

我读了jest文档,但它不太清楚。我将不胜感激,如果有人能为我提供一个例子,如何上述工作,他们是不同的。

EN

回答 1

Stack Overflow用户

发布于 2021-02-25 09:32:56

感谢@sepehr的回答。

我认为通过示例来理解会更容易一些。

快速提示:

  1. 如果您想测试调用次数模拟函数,clear在使用之前
  2. 如果希望确保模拟返回值不会污染其他测试用例,请调用reset
  3. 如果要使用原始方法而不是模拟实现,请调用restore
代码语言:javascript
运行
复制
import {Calculator} from './calculator';

describe('calculator add', function () {
    let calculator = new Calculator();
    const mockAdd = jest.spyOn(calculator, 'add');
    it('mock the add method', function () {
        calculator.add = mockAdd.mockReturnValue(5);
        expect(calculator.add(1, 2)).toBe(5);
    });

    it('because we didnt clear mock, the call times is 2', function () {
        expect(calculator.add(1, 2)).toBe(5);
        expect(mockAdd).toHaveBeenCalledTimes(2);
    });

    it('After clear, now call times should be 1', function () {
        jest.clearAllMocks();
        expect(calculator.add(1, 2)).toBe(5);
        expect(mockAdd).toHaveBeenCalledTimes(1);
    });

    it('we reset mock, it means the mock has no return. The value would be undefined', function () {
        jest.resetAllMocks();
        expect(calculator.add(1, 2)).toBe(undefined);
    });

    it('we restore the mock to original method, so it should work as normal add.', function () {
        jest.restoreAllMocks();
        expect(calculator.add(1, 2)).toBe(3);
    });
});
票数 22
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58151010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档