LoginSignup
0
0

More than 1 year has passed since last update.

mswでmockするときにデータが取得できなかった話(parse-error)

Posted at

結論

テスト用のnode環境では、
mswのエンドポイント定義は、フルパスで設定しないと取得できない。

よい例:

const server = setupServer(
  rest.get('http://localhost:3000/users', (req, res, ctx) => {
    return res(ctx.json({ firstName: 'John' }))
  }),
)

ダメな例:

const server = setupServer(
  // "/users"だけではハンドリングされません!
  rest.get('/users', (req, res, ctx) => {
    return res(ctx.json({ firstName: 'John' }))
  }),
)

経緯

ローカルでフロントのテスト用にmswでAPIレスポンスをモック化したら、データが取得できず、なんで??ってなった。

モック化方法:

mswの公式手順に従い、src/mocks/server.jssrc/setupTests.js(CRA使用プロジェクト)を作成・更新した。

// src/mocks/server.js
const server = setupServer(
  rest.get('/users', (req, res, ctx) => {
    return res(ctx.json({ firstName: 'John' }))
  }),
// src/setupTests.js
import { server } from './mocks/server.js'
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

テスト対象コンポーネント(React、データ取得はrtk-Query使用)

const { users, isSuccess, isLoading, isError, error } = useUsers();

const getContent = () => {
    if (isLoading) {
      return <Skeleton animation="wave" />;
    } else if (isSuccess) {
      return (
        <Container maxWidth="xl">
          {users.ids.map((id) => (
            <StyledUserPreview userId={id} key={id} />
          ))}
        </Container>
      );
    } else if (isError && error) {
      if ('status' in error) {
        return (
          <Alert variant="filled" severity="error">
            An error has occurred:
            {error.status}
          </Alert>
        );
      } else {
        // you can access all properties of `SerializedError` here
        return <div>{error.message}</div>;
      }
    }
  };
  return (
    <div>
      ・・・省略
      {getContent()}
      ・・・省略
    </div>
  );

この時点で出てきたエラー:

 console.warn
    [MSW] Warning: captured a request without a matching request handler:
    
      • GET http://localhost:3000/users
    
    If you still wish to intercept this unhandled request, please create a request handler for it.
    Read more: https://mswjs.io/docs/getting-started/mocks
  console.error
    Error: Error: connect ECONNREFUSED 127.0.0.1:3000

http://localhost:3000/usersで取得しようとして、結局コネクト(ハンドリング)できないやーっていう感じ。

なので、吐いてくれたパスhttp://localhost:3000/usersをそのままserver.jsのやつに書き換えたら、うまくいった~

// src/mocks/server.js
const server = setupServer(
-  rest.get('/users', (req, res, ctx) => {
+  rest.get('http://localhost:3000/users', (req, res, ctx) => {
    return res(ctx.json({ firstName: 'John' }))
  }),

さいごに

公式ドキュメントにも、ちゃんと注意書きとして記載されていることを後から気づいた。
公式ドキュメントをちゃんと読むべし。:laughing:

0
0
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
0
0