在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):mswjs/msw开源软件地址(OpenSource Url):https://github.com/mswjs/msw开源编程语言(OpenSource Language):TypeScript 96.0%开源软件介绍(OpenSource Introduction):Mock Service WorkerMock Service Worker (MSW) is an API mocking library for browser and Node.js. Features
DocumentationExamples
BrowserHow does it work?Browser usage is what sets Mock Service Worker apart from other tools. Utilizing the Service Worker API, which can intercept requests for the purpose of caching, Mock Service Worker responds to captured requests with your mock definition on the network level. This way your application knows nothing about the mocking. Watch a 30 seconds explanation on how Mock Service Worker works in a browser: How is it different?
Usage example// src/mocks.js
// 1. Import mocking utils.
import { setupWorker, rest } from 'msw'
// 2. Define request handlers and response resolvers.
const worker = setupWorker(
rest.get('https://github.com/octocat', (req, res, ctx) => {
return res(
ctx.delay(1500),
ctx.status(202, 'Mocked status'),
ctx.json({
message: 'Mocked response JSON body',
}),
)
}),
)
// 3. Start the Service Worker.
worker.start() Performing a
NodeHow does it work?Although Service Worker is a browser-specific API, this library allows reusing of the same mock definition to have API mocking in Node.js through augmenting native request issuing modules. How is it different?
Usage exampleHere's an example of an actual integration test in Jest that uses React Testing Library and Mock Service Worker: // test/LoginForm.test.js
import '@testing-library/jest-dom'
import React from 'react'
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Login from '../src/components/Login'
const server = setupServer(
rest.post('/login', (req, res, ctx) => {
// Respond with a mocked user token that gets persisted
// in the `sessionStorage` by the `Login` component.
return res(ctx.json({ token: 'mocked_user_token' }))
}),
)
// Enable API mocking before tests.
beforeAll(() => server.listen())
// Reset any runtime request handlers we may add during the tests.
afterEach(() => server.resetHandlers())
// Disable API mocking after the tests are done.
afterAll(() => server.close())
test('allows the user to log in', async () => {
render(<Login />)
userEvent.type(
screen.getByRole('textbox', { name: /username/i }),
'john.maverick',
)
userEvent.type(
screen.getByRole('textbox', { name: /password/i }),
'super-secret',
)
userEvent.click(screen.getByText(/submit/i))
const alert = await screen.findByRole('alert')
// Assert successful login state
expect(alert).toHaveTextContent(/welcome/i)
expect(window.sessionStorage.getItem('token')).toEqual(fakeUserResponse.token)
})
test('handles login exception', () => {
server.use(
rest.post('/login', (req, res, ctx) => {
// Respond with "500 Internal Server Error" status for this test.
return res(
ctx.status(500),
ctx.json({ message: 'Internal Server Error' }),
)
}),
)
render(<Login />)
userEvent.type(
screen.getByRole('textbox', { name: /username/i }),
'john.maverick',
)
userEvent.type(
screen.getByRole('textbox', { name: /password/i }),
'super-secret',
)
userEvent.click(screen.getByText(/submit/i))
// Assert meaningful error message shown to the user
expect(alert).toHaveTextContent(/sorry, something went wrong/i)
expect(window.sessionStorage.getItem('token')).toBeNull()
})
SponsorsGolden Sponsors
Silver Sponsors
Bronze Sponsors
Awards & Mentions
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论