最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jest multiple method calls in tests cause wrong expectations - Stack Overflow

programmeradmin1浏览0评论

just starting to dive into testing world and one thing confuses me. I have class like this:

class TestClass {
  static staticMethod () {
    methodOne();
    methodTwo();
}

and test like this:

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

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

Jest throws an error, that says methodTwo has been called two times instead of one. I Figured, it's because I'm running two tests that calls class static method two times (one time in first test, and second time in second test), hence methodTwo is called two times.

So my question, is it possible somehow to isolate those tests ? When I'm running test one (calling some class method) it shouldn't influence other test results.

Thanks!

just starting to dive into testing world and one thing confuses me. I have class like this:

class TestClass {
  static staticMethod () {
    methodOne();
    methodTwo();
}

and test like this:

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

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

Jest throws an error, that says methodTwo has been called two times instead of one. I Figured, it's because I'm running two tests that calls class static method two times (one time in first test, and second time in second test), hence methodTwo is called two times.

So my question, is it possible somehow to isolate those tests ? When I'm running test one (calling some class method) it shouldn't influence other test results.

Thanks!

Share Improve this question asked Nov 26, 2017 at 15:16 PolisasPolisas 5411 gold badge9 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 16

You're right, by default Jest spies keep their state through your different tests.

To reset them, I personally use :

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

see https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks for more information

发布评论

评论列表(0)

  1. 暂无评论