setupServer()
A function that sets up a request interception layer in NodeJS environment.
setupWorker
instead.Operation
Since Service Worker API cannot run in a non-browser environment, the NodeJS support of request interception is done via a designated node-request-interceptor
library.
Although there is "server" in
setupServer
, the library does not establish any actual servers, but operates by augmenting native request issuing modules (such ashttps
orXMLHttpRequest
). The namespace is chosen for what the logic represents, not how it works internally.
Limitations
There may be certain limitations when reusing request handlers between client and server. For example, if your request handler operates with localStorage
, it wouldn't do so in NodeJS environment, because that API is specific to a browser.
Here are some pieces of advice on how to handle such limitations:
- Introduce any necessary polyfills for browser-specific APIs.
- Break down a response resolver into set of independent functions. That way you can omit the functions that are meant for a browser, and optionally substitute them with compatible NodeJS replacements.
Examples
Typically, setupServer
is used for unit and integration tests, however, it will run in any NodeJS process.
Here's an example of the integration test using Jest and Mock Service Worker to provide a seamless API mocking:
1import { rest } from 'msw'2import { setupServer } from 'msw/node'34const server = setupServer(5 // Describe the requests to mock.6 rest.get('/book/:bookId', (req, res, ctx) => {7 return res(8 ctx.json({9 title: 'Lord of the Rings',10 author: 'J. R. R. Tolkien',11 }),12 )13 }),14)1516beforeAll(() => {17 // Establish requests interception layer before all tests.18 server.listen()19})2021afterAll(() => {22 // Clean up after all tests are done, preventing this23 // interception layer from affecting irrelevant tests.24 server.close()25})2627test('renders a book data', () => {28 // Render components, perform requests, API communication is covered.29})