MSWの門前
MSWをちゃんと使えるようになりたい。
悪い癖だけど周辺記事から読んでしまっている。
あとで書きそうなのでメモ
export const endpoint = process.env.REACT_APP_USE_MOCK_SERVER === 'true' ? process.env.REACT_APP_MOCK_API_ENDPOINT : process.env.REACT_APP_API_ENDPOINT;
実際のモックの実装は src/mocks/resolvers 配下に REST API のリソースごとにファイルを配置し、src/mocks/handler.ts ではどのリクエストをどのハンドラに対応させるかの記述をするのがよい感じです。
src/mocks/ ├── browser.ts ├── handler.ts ├── resolvers │ ├── login.ts │ ├── logout.ts │ ├── posts.ts │ └── users.ts └── server.ts
もはや必須のやつ
JSON レスポンスを返却する ctx.json() メソッドは型引数を受け取ることができます。ctx.json() の引数が型引数と一致しない場合には、型エラーが発生します。
import { setGlobalConfig } from "@storybook/testing-react";
import * as globalStorybookConfig from "./.storybook/preview";
これでStorybook側の設定でmsw.initializeしているのを再利用するというお話だった
ようやくちゃんと読む
そもそもService Workerとは
Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.
A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and Web Storage can't be used inside a service worker.
Why Service Workers?
Mock Service Worker leverages a standardized Service Worker API that is designed to intercept requests on the network level, making the mocking completely seamless. Not only this guarantees an identical application's behavior with and without mocks, but also does not require any changes to the application's code for the sake of mocking. Observe requests in the "Network" of your DevTools, forgetting the mocks are at place.
たしかにネットワークレベルでモックされていればテストのためにコードをどうこうする心配は大幅に削減される
流れ
例 (cited from: https://mswjs.io/docs/getting-started/mocks/rest-api )
// src/mocks/handlers.js
import { rest } from 'msw'
export const handlers = [
rest.post('/login', (req, res, ctx) => {
// Persist user's authentication in the session
sessionStorage.setItem('is-authenticated', 'true')
return res(
// Respond with a 200 status code
ctx.status(200),
)
}),
rest.get('/user', (req, res, ctx) => {
// Check if the user is authenticated in this session
const isAuthenticated = sessionStorage.getItem('is-authenticated')
if (!isAuthenticated) {
// If not authenticated, respond with a 403 error
return res(
ctx.status(403),
ctx.json({
errorMessage: 'Not authorized',
}),
)
}
// If authenticated, return a mocked user details
return res(
ctx.status(200),
ctx.json({
username: 'admin',
}),
)
}),
]
Next.jsで使うときは_app.tsxでinitする。app dirだとRoot Layoutでいいのか?
ここにmocksからのhandlerをimportしてこればよいだけかな?
import { rest } from 'msw'
export const SuccessBehavior = () => <UserProfile />
SuccessBehavior.parameters = {
msw: {
handlers: [
rest.get('/user', (req, res, ctx) => {
return res(
ctx.json({
firstName: 'Neil',
lastName: 'Maverick',
})
)
}),
]
},
}