Skip to content

Conversation

@vidup
Copy link
Contributor

@vidup vidup commented Aug 10, 2024

This PR adds a new feature: returning/resolving values corresponding to validation and anyXXX matchers instead of specific values. The objective is:

  • to speed-up writing tests with categories of values (which matchers are).
  • to accept zod schemas, which can help mock APIs thanks to their related validation schemas.

It works like this:

For matchers of anyXXX format, you can pass them in thenReturn/thenResolve, and it will generate a value that would pass this matcher in assertions.

const mock = m.Mock(hi);
m.when(mock).isCalled.thenReturn(m.anyArray());

mock(); // an array

For zod schemas, you can pass them as well in their dedicated matcher (m.validates). To make this works you will need to install two dependencies:

npm install zod @faker-js/faker @anatine/zod-mock

zod-mock is a package that will generate a valid value for a given zod schema. It requires faker (hence the second dependency).
These dependencies are peerDependencies of Mockit: this specific feature won't work if you didn't create it.

test("thenReturn should accept a Zod schema and return a valid object", () => {
    // In a real world scenario, you will import this schema from the module under test.
    const schema = z.object({
        name: z.string(),
        age: z.number(),
    });
    
    const mock = m.Mock(hi)
    m.when(mock).isCalled.thenReturn(m.validates(schema));
    
    const result = mock();
    expect(result).toMatchObject({
        name: expect.any(String),
        age: expect.any(Number),
    })
});

Thoughs

Honestly I'm not sure if this is really useful, considering the fact that people could just install zod-mock (which they will need to do since I'm not planning on bundling it with Mockit), and could then just call thenReturn(generateMock(schema)).

Todo

  • Make it work on thenResolve
  • remove coupling between anyXXX matchers and zod-mock.
  • decide if this is actually a useful addition.

@vidup vidup added the enhancement New feature or request label Aug 10, 2024
@vidup vidup self-assigned this Aug 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants