MSW 单元测试 API 成功并成功错误场景

发布于 2025-01-19 08:19:23 字数 1775 浏览 4 评论 0原文

我正在使用 MSW 进行本地开发和单元测试。

#API fetch
const { loading, error, data } = useFetch('https://made.up/api/usage')

#handler.js
import { rest } from 'msw'

export const handlers = [
  rest.get('https://made.up/api/usage', (req, res, ctx) => {
    return res(
      ctx.status(301),
      ctx.json({
        id: 1,
        firstName: 'John',
      }),
    )
  }),
]

#server.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'

export const server = setupServer(...handlers)
#setupTests.js
beforeAll(() => {
    server.listen({
      onUnhandledRequest: 'warn',
    })
  })

  afterEach(() => {
    server.resetHandlers()
  })

  afterAll(() => {
    server.close()
  })
#App.test.js
import React from "react";
import { rest } from "msw";
import { render, screen } from "@testing-library/react";
import { server } from "../src/mocks/server";

import App from "../src/App";

test("passes", async () => {
  render(<App />);

  expect(
    // Expect the mocked response to be present in the DOM.
    await screen.findByText(`{"id":1,"firstName":"John"}`)
  ).toBeInTheDocument();
});

test("error", async () => {
  server.use(
    rest.get("https://made.up/api/usage", (req, res, ctx) => {
      return res(
        ctx.status(500),
        ctx.json({
          error: "error"
        })
      );
    })
  );
  render(<App />);

  expect(
    // Expect the mocked error response to be present in the DOM.
    await screen.findByText("Error: error}")
  ).toBeInTheDocument();
});

我正在重写 API 处理程序来测试错误场景。当一起运行时,这两个测试都不会通过。如果我单独运行它们,它们工作得很好。

我错过了什么步骤吗?或者我们可以使用 MSW 以其他方式测试相同的 API 的不同响应?

I am using MSW for local development and unit testing.

#API fetch
const { loading, error, data } = useFetch('https://made.up/api/usage')

#handler.js
import { rest } from 'msw'

export const handlers = [
  rest.get('https://made.up/api/usage', (req, res, ctx) => {
    return res(
      ctx.status(301),
      ctx.json({
        id: 1,
        firstName: 'John',
      }),
    )
  }),
]

#server.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'

export const server = setupServer(...handlers)
#setupTests.js
beforeAll(() => {
    server.listen({
      onUnhandledRequest: 'warn',
    })
  })

  afterEach(() => {
    server.resetHandlers()
  })

  afterAll(() => {
    server.close()
  })
#App.test.js
import React from "react";
import { rest } from "msw";
import { render, screen } from "@testing-library/react";
import { server } from "../src/mocks/server";

import App from "../src/App";

test("passes", async () => {
  render(<App />);

  expect(
    // Expect the mocked response to be present in the DOM.
    await screen.findByText(`{"id":1,"firstName":"John"}`)
  ).toBeInTheDocument();
});

test("error", async () => {
  server.use(
    rest.get("https://made.up/api/usage", (req, res, ctx) => {
      return res(
        ctx.status(500),
        ctx.json({
          error: "error"
        })
      );
    })
  );
  render(<App />);

  expect(
    // Expect the mocked error response to be present in the DOM.
    await screen.findByText("Error: error}")
  ).toBeInTheDocument();
});

I am overriding the API handler to test the error scenario. Both the tests do not pass when run together. If I run them individually, they work fine.

Am I missing any step? or we can test the same API for different responses in some other way using MSW?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅忆 2025-01-26 08:19:23

我已经解决了这个问题。

server.use(
    rest.get("https://made.up/api/usage", (req, res, ctx) => {
      return res(
        ctx.status(500),
        ctx.json({
          error: "error"
        })
      );
    })
  );

上面的代码永久覆盖 API 处理程序。如果我们想一次性覆盖,由于

server.use(
    rest.get("https://made.up/api/usage", (req, res, ctx) => {
      return res.once(
        ctx.status(500),
        ctx.json({
          error: "error"
        })
      );
    })
  );

这个原因,我的测试没有一起运行,但单独运行时工作正常。

I have got a fix for this issue.

server.use(
    rest.get("https://made.up/api/usage", (req, res, ctx) => {
      return res(
        ctx.status(500),
        ctx.json({
          error: "error"
        })
      );
    })
  );

The above code is permanently overriding the API handler. If we want to override one-time, the

server.use(
    rest.get("https://made.up/api/usage", (req, res, ctx) => {
      return res.once(
        ctx.status(500),
        ctx.json({
          error: "error"
        })
      );
    })
  );

Due to this reason, my tests were not running together but working fine when run individually.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文