首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >成功与错误场景中的MSW单元测试API

成功与错误场景中的MSW单元测试API
EN

Stack Overflow用户
提问于 2022-04-06 09:43:36
回答 1查看 1.1K关注 0票数 0

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

代码语言:javascript
复制
#API fetch
const { loading, error, data } = useFetch('https://made.up/api/usage')
代码语言:javascript
复制
#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',
      }),
    )
  }),
]
代码语言:javascript
复制
#server.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'

export const server = setupServer(...handlers)
代码语言:javascript
复制
#setupTests.js
beforeAll(() => {
    server.listen({
      onUnhandledRequest: 'warn',
    })
  })

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

  afterAll(() => {
    server.close()
  })
代码语言:javascript
复制
#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处理程序来测试错误场景。在一起运行时,这两个测试都没有通过。如果我单独运行它们,它们就能正常工作。

我是不是错过了任何一步?或者我们可以用其他方式测试相同API的不同响应,使用MSW?

EN

回答 1

Stack Overflow用户

发布于 2022-04-06 12:08:50

我已经解决了这个问题。

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

上面的代码将永久覆盖API处理程序。如果我们要覆盖一次,则

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

由于这个原因,我的测试不是一起运行的,而是单独运行时工作得很好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71764462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档