Skip to content

spyOn docs misleading? #4828

@lydell

Description

@lydell

The jest.spyOn example in the docs looks like this:

const video = require('./video');

test('plays video', () => {
  const spy = jest.spyOn(video, 'play');
  const isPlaying = video.play();

  expect(spy).toHaveBeenCalled();
  expect(isPlaying).toBe(true);

  spy.mockReset();
  spy.mockRestore();
});

My questions is: Is that a good example? If an expectation fails, later tests that also use video will unexpectedly get a mocked .play() method.

Here's a concrete example:

const product = {
  getPrice: () => 1337,
};

describe("product", () => {
  test("getPrice 1", () => {
    const spy = jest.spyOn(product, "getPrice").mockImplementation(() => 0);
    // This expectation fails (`0 !== 42`).
    expect(product.getPrice()).toBe(42);
    spy.mockRestore();
  });

  test("getPrice 2", () => {
    // This expectation _unexpectedly_ fails, because `spy.mockRestore()` never
    // gets a chance to run.
    expect(product.getPrice()).toBe(1337);
  });
});

Above, both tests are failing and the user has to find out which test to "fix" first.

Lots of people, including me, copy stuff from docs all the time. So it is a good thing if the examples are really good :)

Unfortunately, I don't know what the best practice is here, otherwise I could have made a PR.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions