timkindberg / jest-when

Jest support for mock argument-matched return values.
MIT License
734 stars 38 forks source link

Trainings with asymmetric matchers not overridable even with re-ordering #107

Open ChristopherChudzicki opened 3 months ago

ChristopherChudzicki commented 3 months ago

Context: I use jest-when for mocking API responses, typically through a function like makeRequest(method, url, requestBody). Often we don't care about the request body, and often we want to use an assymetric matcher for the URL (for flexibility in query parameters).

I've run into an issue where asymmetric matchers seem to either override everything or are do not work at all. For example:

If the asymmetric matcher is used first, it seems not to work at all:

import { when } from "jest-when"

test("when using asymmetric matchers", () => {
  const fn = jest.fn()
  when(fn).calledWith(expect.anything()).mockReturnValue("fallback")
  when(fn).calledWith("cat").mockReturnValue("meow")
  expect(fn("cat")).toBe("meow")     // PASSES
  expect(fn("dog")).toBe("fallback") // FAILS... returns undefined
})

Reversing the order does not help:

import { when } from "jest-when"

test("when using asymmetric matchers [reordered]", () => {
  const fn = jest.fn()
  when(fn).calledWith("cat").mockReturnValue("meow")
  when(fn).calledWith(expect.anything()).mockReturnValue("fallback")

  expect(fn("cat")).toBe("meow")     // FAILS ... returns "fallback"
  expect(fn("dog")).toBe("fallback") // PASSES
  // NOTE: This behavior seems expected to me. The wider match was most recently second.
})

Edit: This is with:

timkindberg commented 1 month ago

We do have support for fallback behaviors already: https://github.com/timkindberg/jest-when?tab=readme-ov-file#supports-default-behavior