【问题标题】:How to mock data response using msw and axios.create() instance如何使用 msw 和 axios.create() 实例模拟数据响应
【发布时间】:2022-12-30 02:17:44
【问题描述】:

我想使用 msw 进行模拟数据获取。我有一个 axios 实例配置,标题中有授权。

这是我的实例.ts

import axios from 'axios';

const BASE_URL = process.env.REACT_APP_BASE_URL;

const createInstance = () => {
  const instance = axios.create({
    baseURL: BASE_URL,
    headers: {
      'content-type': 'application/json',
      Accept: 'application/json',
    },
  });

  instance.interceptors.request.use(
    (config) => {
      const token = window.localStorage.getItem('token');
      if (token) {
        return {
          ...config,
          headers: { Authorization: `Bearer ${token}` },
        };
      }
      return null;
    },
    (err) => Promise.reject(err)
  );
  return instance;
};

export default createInstance();

这是我的 handlers.js

export const handlers = [
  rest.get(BASE_URL, (req, res, ctx) => {
    return res(
      ctx.json(ctx.json({
        user: {
          images: [
            {
              url: 'Testing Image',
            },
          ],
          display_name: 'Kitty_Puff',
          country: 'ID',
          followers: {
            total: 2000,
          },
          external_urls: {
            spotify: 'No Url Here',
          },
        },
      })
    ));
  }),
]

还有我的 profile.test.js:

test('Should render profile page properly', async () => {
  render(<Profile />);

  const name = await screen.findByText('Kitty_Puff');

  expect(name).toBeVisible();
});

我运行测试但返回失败,因为没有文本“Kitty_Puff”。我做了 screen.debug 以查看它呈现的内容,它呈现了除数据响应之外的所有内容。我怎么能做这个模拟 api 调用?

【问题讨论】:

  • 你打电话给server.listen()吗?

标签: reactjs axios msw


【解决方案1】:

我有同样的问题。我的问题是,即使你在获取,msw 知道你在使用 axios 吗? 因为我正在使用 dispatch 触发一个动作,然后它调用服务器,但我不知道 msw 拦截器是否正常工作。

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2021-07-17
    • 1970-01-01
    • 2020-06-11
    • 2018-12-25
    • 2022-10-06
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多