Javascript 如何在每次测试之前重置 Jest 模拟函数调用计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47812801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:57:12  来源:igfitidea点击:

How to reset Jest mock functions calls count before every test

javascriptunit-testingjestjs

提问by Alex Efremov

I'm new to Jest, I'm trying to use it for testing if a function was called or not. I noticed the mock.calls.length is not resetting for every test but accumulating. How can I make it 0 before every test? I don't want my next tests depends on the results of the previous.

我是 Jest 的新手,我试图用它来测试一个函数是否被调用。我注意到 mock.calls.length 并没有为每个测试重置,而是在累积。如何在每次测试前将其设为 0?我不希望我的下一个测试取决于前一个的结果。

I know there is beforeEach in Jest - should I use it? What is the best way to reset mock.calls.length? Thank you.

我知道 Jest 中有 beforeEach - 我应该使用它吗?重置 mock.calls.length 的最佳方法是什么?谢谢你。

A code example:

一个代码示例:

Sum.js:

总和.js:

import local from 'api/local';

export default {
  addNumbers(a, b) {
    if (a + b <= 10) {
      local.getData();
    }
    return a + b;
  },
};

Sum.test.js

Sum.test.js

import sum from 'api/sum';
import local from 'api/local';
jest.mock('api/local');

// For current implementation, there is a difference 
// if I put test 1 before test 2. I want it to be no difference

// test 1
test('should not to call local if sum is more than 10', () => {
  expect(sum.addNumbers(5, 10)).toBe(15);
  expect(local.getData.mock.calls.length).toBe(0);
});

// test 2
test('should call local if sum <= 10', () => {
  expect(sum.addNumbers(1, 4)).toBe(5);
  expect(local.getData.mock.calls.length).toBe(1);
});

回答by Alex Efremov

One way I found to handle it: to clear mock function after each test:

我发现处理它的一种方法:在每次测试后清除模拟功能:

To add to Sum.test.js:

添加到 Sum.test.js:

afterEach(() => {
  local.getData.mockClear();
});

If you'd like to clear all mock functions after each test, use clearAllMocks

如果您想在每次测试后清除所有模拟功能,请使用clearAllMocks

afterEach(() => {
  jest.clearAllMocks();
});

回答by Daniel Marín

As @AlexEfremov pointed in the comments. You may want to use clearAllMocksafter each test:

正如@AlexEfremov 在评论中指出的那样。您可能希望clearAllMocks在每次测试后使用:

afterEach(() => {
    jest.clearAllMocks();
});

Take in mind this will clear the call count of every mock function you have, but that is probably the right way.

请记住,这将清除您拥有的每个模拟函数的调用计数,但这可能是正确的方法。