Skip to main content
Version: 3.x.x

Testing Stubbing

You can easily create the stubs helpers for the test setup using the existing development environment.

Stub helpers

Below is an example of use with the MSW library.

import { setupServer } from "msw/node";

export const server = setupServer();

const createStub = <Request extends RequestInstance>(request: Request, fixture?: ExtractResponseType<T>) => {
server.use(
// Describe the requests to mock.
rest.get(request.endpoint, (req, res, ctx) => {
return res(ctx.json(fixture));
}),
);
};

Stub tests

Then we can use the prepared util along with the requests prepared during development.

import { getBook } from "api/books";

beforeAll(() => {
// Establish requests interception layer before all tests.
server.listen();
});
afterAll(() => {
// Clean up after all tests are done, preventing this
// interception layer from affecting irrelevant tests.
server.close();
});
test("renders a book details component", () => {
const book = { bookId: 1, bookTitle: "Lord of the Rings" };
createStub(getBook, book);

// Render component, perform request, API communication is covered above.
renderComponent();

// Some assertions
});