AI Briefing
KO

Resolving MSW Mocking Code Duplication: Reusing Storybook Stories in Jest Tests with Custom Render

·2022.03.17 09:00

Key point

A Custom Render wrapper automatically applies MSW mocks from Storybook stories to Jest, eliminating duplicate code.

Details

To resolve the issue of duplicated MSW (Mock Service Worker) mocking code in Storybook and Jest testing environments, this article proposes a method to reuse mocks defined in stories within Jest. Previously, even when transforming story components via @storybook/testing-react, it was cumbersome to rewrite mock handlers using server.use() within Jest test code.

Automatic Mock Application via Custom Render

To solve this problem, a Custom Render was implemented by wrapping the render function from @testing-library/react. This wrapper checks parameters.msw.handlers in the story during rendering and automatically calls server.use(), thereby removing mocking logic from test code. Additionally, to prevent side effects between tests, server.resetHandlers() is called in the afterEach hook to reset the mock state.

Resolving URL Path Issues in Node.js Environments

MSW only allows absolute paths in Node.js environments, causing compatibility issues with application code that uses relative paths. To address this, Tagged Template Literals were utilized. By defining a testUrl function that prepends the http://localhost prefix only when the execution environment is Node.js (using the detect-node library), both application and test code can write URLs using relative paths while still performing MSW mocking correctly.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.