jest-cucumber icon indicating copy to clipboard operation
jest-cucumber copied to clipboard

Jest mocks not being correctly applied for each scenario

Open number33 opened this issue 4 years ago • 2 comments

I noticed some odd behaviour when mocking methods in scenarios. It appears that the last scenario's mock applies to all of the tests, as opposed using the mocked value in each scenario.

Here is a contrived example for now, as I don't have my code in github

Test step file

import fnTest from "../../fnTest";
import { functionUnderTest } from "../../fileUndertest";

const mockFn = jest.fn();
jest.mock("~/fnTest", () => {
  return jest.fn().mockImplementation(() => {
    return { testFn: mockFn };
  });
});

const feature = loadFeature("../features/test.feature", { loadRelativePath: true });

defineFeature(feature, test => {

  test("Testing scenario 1", ({given}) => {
    mockFn.mockReturnValue("test1");
    given("just testing 1", () => expect(functionUnderTest).toEqual("test1"));
  });

  test("Testing scenario 2", ({given}) => {
    mockFn.mockReturnValue("test2");
    given("just testing 1", () => expect(functionUnderTest).toEqual("test2"));
  });
});

fnTest class

class fnTest {
  constructor() {}
  testFn() {
    return "test"
  }
}

export default fnTest;

fileUndertest

import fnTest from "./fnTest";

export const functionUnderTest = () => {
  const x = new testFn();
  return x.testFn();
}

What actually happens is:

  • "Testing scenario 1" will fail asserting that "test2" is not equal to "test1"
  • "Testing scenario 2" will pass asserting that "test2" is equal to "test1"

If I swap the order of scenarios in my feature file, the inverse test results will happen, meaning that "Test scenario 2" will fail and "Test scenario 1" will pass.

What I expect to happen is that "Testing scenario 1" correctly sets the mocked return value such that I the assertion will pass.

number33 avatar Oct 09 '20 13:10 number33

@number33 you should check out cucumber-jest, it doesn't have this problem. it's a jest transformer for executing cucumber tests with jest. It allows you to use the cucumber api to define steps, hooks, world, etc. and not a custom api like this library.

mainfraame avatar Dec 05 '20 21:12 mainfraame

I'm having the same issue with mock.spyOn, is there really no way around this ?

ThibaudMZN avatar Sep 21 '22 22:09 ThibaudMZN

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

github-actions[bot] avatar Apr 09 '24 02:04 github-actions[bot]