如何解决测试React组件中的导航
我想测试按下提交按钮时URL是否更改。作为测试的一部分,我正在检查初始URL为“ / auth”,并且该URL为“ /”。
但是,使用初始的url测试失败了。
测试:
it("displays an authcode and submit button",async() => {
history = createMemoryHistory();
const root = document.createElement('div');
document.body.appendChild(root);
render(
<MemoryRouter initialEntries={["/auth"]}>
<App />
</MemoryRouter>,root
);
expect(screen.queryByTestId('bad-code-message').classList.contains('hidden')).toBe(true);
expect(screen.getByLabelText('Auth code:')).toBeVisible();
expect(screen.getByRole('button')).toBeVisible();
expect(location.pathname).toBe("/auth");
});
应用程序组件:
import React from "react";
import { Route } from "react-router-dom";
import { ProtectedRoute } from './ProtectedRoute';
import { CreateProfileWithRouter } from './CreateProfileComponent';
import { ActivityList } from './ActivityListComponent';
import { TokenEntryWithRouter } from './TokenEntryComponent';
export class App extends React.Component {
render() {
return (
<div>
<ProtectedRoute exact path="/" component={ActivityList} />
<Route path="/login" component={CreateProfileWithRouter} />
<Route path="/auth" component={TokenEntryWithRouter} />
</div>
);
}
}
结果:
expect(received).toBe(expected) // Object.is equality
Expected: "/auth"
Received: "/"
解决方法
经过反复试验,我发现了一些问题。 “ /”是初始网址,但我不知道如何更改。我正在传递组件将导航到的URL,并在开始时断言“ /”是该URL,并且在测试导航时,我断言该URL已更改为传入的URL。
我也在使用路由器而不是MemoryRouter。我对docs有一个预感,就是以一种可以测试的方式更改了传递给组件(带有“ withRouter”)的历史道具。
所有测试之前:
beforeEach(() => {
jest.resetAllMocks();
createPermanentAuthSpy = jest.spyOn(yasClient,"createPermanentAuth");
history = createMemoryHistory();
const root = document.createElement('div');
document.body.appendChild(root);
render(
<Router history={history}>
<TokenEntryWithRouter navigateToOnAuthentication="/dummy" />
</Router>,root
);
token = screen.getByLabelText('Auth code:');
expect(screen.queryByTestId('bad-code-message').classList.contains('hidden')).toBe(true);
expect(history.location.pathname).toBe("/");
});
测试导航:
it("navigates to '/',when a good token is entered.",async() => {
createPermanentAuthSpy.mockImplementationOnce(() => Promise.resolve(true));
await act(async() => {
fireEvent.change(token,{ target: { value: '1' } });
fireEvent.submit(screen.getByTestId('create-permanent-auth'));
});
expect(createPermanentAuthSpy).toHaveBeenCalledTimes(1);
expect(token.classList.contains('valid-data')).toBe(true);
expect(screen.queryByTestId('bad-code-message').classList.contains('hidden')).toBe(true);
expect(history.location.pathname).toBe("/dummy");
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。