MSW
To generate mocks, define the mock
property to true
and a mock of MSW
will be generated in the target file. Visit the MSW documentation to configure MSW correctly in your project.
Example of orval.config.js
module.exports = {'petstore-file-transfomer': {output: {mode: 'single',target: './src/petstore.ts',schemas: './src/model',mock: true,},input: {target: './petstore.yaml',},},};
The mock definition consists of the following three functions.
- A function that returns a mocked value of a schema object
- A function that returns the value of binding the mock object to the HTTP request handler of MSW
- A function that returns an array that aggregates all handlers in the file.
A Function That Returns a Mocked Value of a Schema Object
A function that returns a mock object will be generated as shown below:
import { faker } from '@faker-js/faker';export const getShowPetByIdResponseMock = (overrideResponse: Partial<Pet> = {},): Pet => ({id: faker.number.int({ min: undefined, max: undefined }),name: faker.string.alpha(20),tag: faker.string.alpha(20),...overrideResponse,});
The value is implemented in faker.js
.
To overwrite part of the object, modify the mock property by specifying it as a function argument.
import { getShowPetByIdMock } from 'pets.msw';const pet = getShowPetByIdResponseMock({ name: 'override' });console.log(pet);// => { id: 7272122785202176, name: "override", tag: undefined }
A Function That Returns the Value of Binding the Mock Object to the HTTP Request Handler of MSW
A function is generated that returns the value of the mock object bound to the MSW HTTP request handler as shown below:
import { HttpResponse, delay, http } from 'msw';export const getShowPetByIdMockHandler = (overrideResponse?:| Pet| ((info: Parameters<Parameters<typeof http.get>[1]>[0],) => Promise<Pet> | Pet),) => {return http.get('*/pets/:petId', async (info) => {await delay(1000);return new HttpResponse(JSON.stringify(overrideResponse !== undefined? typeof overrideResponse === 'function'? await overrideResponse(info): overrideResponse: getShowPetByIdResponseMock(),),{status: 200,headers: {'Content-Type': 'application/json',},},);});};
To overwrite the mocked HTTP response object, provide the object by specifying it as a function argument.
import { Pet } from './gen/model/pet';import { getShowPetByIdMockHandler } from 'petstore.msw';const pet: Pet = { id: 1, name: 'test', tag: 'test' };const showPetByIdMockHandler = getShowPetByIdMockHandler(pet);console.log(showPetByIdMockHandler);// => Object { info: {…}, isUsed: false, resolver: async getShowPetByIdMockHandler(), resolverGenerator: undefined, resolverGeneratorResult: undefined, options: {} }
It is also possible to pass a function as an argument, which will be called every time a request is made to the API.
getShowPetByIdMockHandler((info) => {const body = await info.request.json();return { message: `body: ${body}` };});
For example, to use the generated mock in a test to verify that the API was called, do as follows:
import { expect, vi } from 'vitest';import { getShowPetByIdMock, getShowPetByIdMockHandler } from 'pets.msw';const mockFn = vi.fn();const mock = [getShowPetByIdMockHandler((info) => {const body = await info.request.json();mockFn(body);return getShowPetByIdResponseMock();}),];expect(mockFn).toHaveBeenCalledTimes(1);
A Function That Returns an array That Aggregates All Handlers in the File.
Aggregate all functions that return handlers and generate a function that returns as an array as below:
export const getPetsMock = () => [getListPetsMockHandler(),getCreatePetsMockHandler(),getShowPetByIdMockHandler(),];
Run the MSW server using this function.
import { getPetsMock } from 'petstore.msw';import { setupServer } from 'msw/node';const server = setupServer();server.use(...getPetsMock());
You can also turn on indexMockFiles
which will allow you dynamically import all mock handlers.
// node.tsimport * as mocks from './endpoints/index.msw';import { setupServer } from 'msw/node';const handlers = Object.entries(mocks).flatMap(([, getMock]) => getMock());const server = setupServer(...handlers);export { server };