【发布时间】:2021-03-27 21:10:51
【问题描述】:
我在useEffect 中发出axios POST 请求,一旦收到值,我就会使用setState 更新我的链接。因此,我想为这个业务逻辑编写一个单元测试。这是我的组件代码。
export function Login() {
const browserUrl = window.location.href;
const [LoginUrl, setLoginUrl] = useState<string>('');
useEffect(() => {
const response = axios.post<LoginUrl>('https://somedomain/getLoginUrl', {
data: browserUrl,
});
response.then((res: LoginUrl) => {
setLoginUrl(res.LoginUrl);
});
}, []);
return (
<>
<LoginLink data-testid="getUrl" href={LoginUrl} style={{ cursor: 'pointer' }}>
LogIN
</LoginLink>
</>
);
}
这是我的单元测试代码。我正在使用 react-testing-library 和 jest。
it('should display loginurl', async () => {
const { getByTestId } = render(<Login />);
axiosMock.post('https://somedomain/getLoginUrl', { data: 'abcgd' }).then(() => {
res: 'asxed';
});
const url = await waitFor(() => getByTestId('show-data'));
expect(url.getAttribute('href')).toEqual('asxed');
});
我的测试从不更新LoginUrl 并且始终具有初始值。我的假设是我没有写出正确的 async 测试或反应钩子测试方法。
【问题讨论】:
标签: reactjs unit-testing jestjs react-hooks react-testing-library