marchaos / jest-mock-extended

Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
MIT License
810 stars 56 forks source link

Mocks evaluate to `undefined` when used with expect.anything() or expect.any() #105

Open eliykat opened 1 year ago

eliykat commented 1 year ago

Mock objects do not work as I expect with expect.anything() (which should match any non-null value) or expect.any() (which should match a given prototype).

Mock objects are evaluated as undefined in these contexts.

Example:

    class MyClass {
      someProperty: string;
    }
    const myClassMock = mock<MyClass>();
    const spyFn = jest.fn();

    spyFn(myClassMock);

    // These all pass:
    expect(myClassMock).not.toBeFalsy();
    expect(myClassMock).not.toEqual(undefined);

    // These all fail:
    expect(myClassMock).toEqual(expect.any(MyClass)); // Expected: Any<MyClass>, Received: undefined
    expect(myClassMock).toEqual(expect.anything());  // Expected: Anything, Received: undefined
    expect(spyFn).toBeCalledWith(expect.anything());  //  Expected: Anything, Received: undefined

To give a bit more detail about what I'm trying to achieve, I want to assert a call to a service using toBeCalledWith. The method call uses some values that I want to assert, and some mock objects (returned by mocked dependencies) which I don't care about. e.g.

dependency = mock<Dependency>();
dependency.getKey.mockResolvedValue(mock<Key>());

// assume that sut calls dependency.getKey and passes to uploadService
sut.someMethod("testValue");

expect(uploadService.upload).toHaveBeenCalledWith(expect.anything(), "testValue");

Is this a misuse of the jest-mock-extended mock objects, or is there something I'm missing in how I'm trying to use them?

PS. love the library otherwise, it's a much needed bridge between jest and TS. Thanks for your work.

EDIT: the same issue occurs when using the jest-mock-extended any() matcher. I guess the issue is more how it's evaluated in the toBeCalledWith/toEqual methods than the specific matcher used within those methods.