LoginSignup
2
1

MSW導入詰まったところ

Last updated at Posted at 2023-08-29

はじめに

MSWを導入するにあたり遭遇したエラーやWarning、悩んだことをまとめます。

開発環境

  • webpack: ^4.44.2
  • msw: ^0.48.3
    • rest api

Warning: captured a request without a matching request handler

問題点

リクエストハンドラに登録されていないリクエストがある場合に発生する。

解決方法

  • リクエストハンドラにWarningが出ているリクエストを追加する。
rest.get('/warning/request/path', (req, res, ctx) => {
    return res(ctx.json({ text: 'test' }))
})
  • worker(あるいはserver)を開始する際にハンドルしていないリクエストのWarningを出さないように設定する。
worker.start({
  onUnhandledRequest: 'bypass',
})

参考: https://mswjs.io/docs/api/setup-worker/start#onunhandledrequest

クエリパラメータの値によってレスポンスを変えたい

問題点

使用しているAPIが/api/?command=xxxのようにクエリパラメータでエンドポイント名を指定するような設計になっている。
下記のように、リクエストハンドラにクエリパラメータ付きで登録してもエンドポイント名でリクエストを分岐させることはできない。(Warningが出る)

rest.get('/api/?command=aaa', (req, res, ctx) => {
    return res(ctx.json({ text: 'test' }))
}),
rest.get('/api/?command=bbb', (req, res, ctx) => {
    return res(ctx.json({ text: 'test' }))
})

解決方法

/apiのリクエストは一旦すべてインターセプトし、commandパラメータの値でレスポンスを分岐させる。

rest.get('/api', (req, res, ctx) => {
    const commandName = req.url.searchParams.get('command')
    
    switch (commandName) {
        case 'aaa':
            return res(ctx.json({ text: 'aaa' }))
        case 'bbb':
            return res(ctx.json({ text: 'bbb' }))
        default:
            return
    }
  }
})

参考: https://mswjs.io/docs/recipes/query-parameters

Expected response resolver to return a mocked response Object but got undefined. The original response is going to be used instead

image.png

問題点

上記「クエリパラメータの値によってレスポンスを変えたい」で使用した解決方法で発生したWarning。
上記例でdefaultの場合にundefinedを返しているため発生していた。

mswのバージョン0.40.0以降のであれば発生しないが、バージョン指定が^0.48.3になっていたため発生した。

解決方法

上記例のdefaultの返り値としてreq.passthrough()を返す。
これによりMSWでモックを返すことなく、そのまま本来のエンドポイントにリクエストが送信される。

default: 
    return req.passthrough()

参考: https://mswjs.io/docs/api/request/passthrough

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1