Paul Razvan Berg
Paul Razvan Berg

Reputation: 21410

Understanding state in jest tests that use spyOn

Suppose that I have a test file foo.test.ts that looks like this:

describe("foo", function() {
  let myMock;

  beforeAll(function() {
    myMock = jest.spyOn(someObject, "someMethod");
  });

  test("my test", function() {
    beforeEach(function() {
      myMock.mockReturnValue("someValue");
    });
    ...
  });

  afterAll(function() {
    myMock.mockRestore();
  });
});

I'm using this pattern because I've seen it recommended in other StackOverflow answers. I wish to understand how Jest works though.

Do I really need to store the mock in a variable, or can I do this?

describe("foo", function() {
  test("my test", function() {
    beforeEach(function() {
      jest.spyOn(someObject, "someMethod").mockReturnValueOnce("someValue");
    });
    ...
  });
});

Notice that I'm using mockReturnValueOnce instead of mockReturnValue.

I ran both implementations and they work fine, but I wonder whether I can say that they are equivalent? Will the "someMethod" function, part of "someObject", not be retained as a mock across other tests from other files?

Upvotes: 1

Views: 664

Answers (1)

Yousaf
Yousaf

Reputation: 29282

jest.spyOn() returns a jest mock function and you want to store the returned mock function in a variable so that you can make assertions.

If you don't store the mock function returned by jest.mock(), then how will you make assertions? All the methods, provided by jest, that can be called on a mock function, can't be called without having a reference to the mock function.

If you just want to mock a return value and not make any assertions on the mocked function, then you don't need to save the reference. Generally, when you mock a function, you want to make assertions like how many times it was called, what arguments it was called with, etc.

Will the "someMethod" function, part of "someObject", not be retained as a mock across other tests from other files?

someMethod will only be mocked in the test file where you mock it. It won't affect the other test files.

Upvotes: 1

Related Questions