marchaos / jest-mock-extended

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

strictmock functionality #14

Open atishnazir opened 4 years ago

atishnazir commented 4 years ago

Trying to figure out whether there a straightforward manner to assert failure on unexpected mock invocations. Using the latest code an unexpected invocation results in an undefined, which in the case of Promises bubbles it's way through the SUT.

I currently employ a workaround where I hang assert raising implementations after my other .calledWith (the calledWiths are evaluated in order of declaration, so the fall through has to be the last one), e.g.

const mockApi = mock<APIClass>();

// mockApi being provided to SUT
mockApi.get
            .calledWith(CORRECT_API, "/some-path", anyObject())
            .mockResolvedValue(response);

// hook to catch errant mockApi calls
mockApi.get
            .mockImplementation(strictMockFallThrough);

sut = new Sut(mockApi);
// this should only hit CORRECT_API
expect(sut.refresh()).toStrictEqual([item1, item2, item3]);

However this is suboptimal as firstly the strictmock semantic has to be implemented in multiple places throughout a test rather than once at mock creation. The second problem is that whilst Jest itself uses exceptions for signalling test failure, if mocked method returns promises this exception is turned into a Promise.reject rather than test assertion. Perhaps something like:

expect(mockApi.get).unexpectedly.toHaveBeenCalledTimes(0);

Google Mock offers strictmock adapters, shows the gist.

marchaos commented 4 years ago

Hey,

So it seems that you want to only allow a specific set of args to calledWith, otherwise you wan to fail the test:

Something like:

mockApi.get
            .calledWith(CORRECT_API, "/some-path", anyObject())
            .mockResolvedValue(response)
            .otherwise(fail('something'));

Am I following that right? As you mention, something like this might be hard in the case of promises as exception will get caught in the reject.

atishnazir commented 4 years ago

Hi, Yes; I'm quite used to the semantics of GoMock, TypeMoq, GoogleMock where you can put quite tight constraints on Mock behaviour. The Promise conversion issue is an annoyance, but it's really a issue of Jest that it uses an Assertion throw (there are workaround here by making an assertions re-entrant and getting expect to hook off that, I've slapped example at end).

Your illustrative API reads well, it's the sort of thing I'm looking for. In usage it might be ambigous what should happen in the test code without creating aggregating matchers:

mockAPI.get
            .calledWith(API, "/pricelist", anyObject())
            .mockResolvedValueOnce(pricelistResponse)
            .otherwise(fail("unexpected API call"));

mockAPI.get
            .calledWith(API, "/inventory", anyObject())
            .mockResolvedValueOnce(inventoryResponse)
            .otherwise(fail("unexpected API call"));

const value = sut.getTotalStockValue();

In the above example, my test should:

Cheers.

Here's the gist of resurfacing swallowed assertions. It's a bit yuck:

describe("surfacing swallowed assertion hack", () => {
    let horribleHook: Error|undefined;

    function fauxExpect<T>(expression: T): jest.Matchers<T> {
        const result = expect(expression);

        if (horribleHook) {
            throw horribleHook
        }
        return result;
    }

    function fail(reason: string) {
        horribleHook = new AssertionError({message: reason});
        throw horribleHook;
    }

    function fauxMock() {
        fail("oh noes, I don't want to be called");
    }

    function sut(callMock: boolean): boolean {
        try {
            if (callMock) {
                fauxMock();
            }
        } catch(e) {
            console.warn("swallowing assertion");
        }
        return true;
    }

    beforeEach(() => {
        horribleHook = undefined;
    });

    test("example of swallowed assertion", () => {
        fauxExpect(sut(false)).toBeTruthy();
        fauxExpect(sut(true)).toBeTruthy();
    });
});