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.
})
Context: I use
jest-when
for mocking API responses, typically through a function likemakeRequest(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:
Reversing the order does not help:
Edit: This is with: