开玩笑测试中的多个方法调用会导致错误的期望

Pol*_*sas 2 javascript unit-testing jestjs

刚刚开始深入测试世界,有一件事让我感到困惑。我有这样的课:

class TestClass {
  static staticMethod () {
    methodOne();
    methodTwo();
}
Run Code Online (Sandbox Code Playgroud)

并像这样测试:

test('should call methodOne function', () => {
  TestClass.staticMethod();
  expect(methodOne).toHaveBeenCalled();
});

test('should call methodTwo function', () => {
  Test.staticMethod();
  expect(methodTwo).toHaveBeenCalled();
  expect(methodTwo).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)

Jest 抛出一个错误,说 methodTwo 被调用了两次而不是一次。我想,这是因为我正在运行两个测试,两次调用类静态方法(第一次测试中一次,第二次测试中第二次),因此 methodTwo 被调用了两次。

所以我的问题是,是否有可能以某种方式隔离这些测试?当我运行测试一(调用某个类方法)时,它不应该影响其他测试结果。

谢谢!

Mat*_*prz 6

你是对的,默认情况下,Jest 间谍通过不同的测试保持他们的状态。

要重置它们,我个人使用:

afterEach(() => {
  jest.clearAllMocks()
})
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks