【发布时间】: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()吗?