我没有模拟 axios 请求,而是尝试使用 msw 测试组件,但是在请求之后我没有得到组件中内容的可见性,我做错了什么?
我的组件
import React, {useEffect, useState} from 'react'
import axios from "axios";
export default function TestPage() {
const [testData, setTestData] = useState('')
useEffect(() => {
const getSomeData = async () => {
const data = await axios.get('https://jsonplaceholder.typicode.com/todos/1')
setTestData(data.data.title)
}
getSomeData()
}, [])
return (
<div className='test'>
<h1>{testData}</h1>
</div>
)
}
我的测试文件
import React from 'react'
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import {render, act, screen} from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import TestPage from "../testPage";
const allUsers = [
{title:'User'}
]
const server = setupServer(
rest.get('https://jsonplaceholder.typicode.com/todos/1', async (req, res, ctx) => {
return res(ctx.json( {data: allUsers} ));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers())
afterAll(() => server.close());
test('loads and displays greeting', async () => {
await act(async () => {
await render(<TestPage/>)
})
await screen.findByText('User') //I have no response content here
screen.debug()
})