【问题标题】:Testing navigation in React component在 React 组件中测试导航
【发布时间】:2020-09-11 22:04:23
【问题描述】:

当按下提交按钮时,我想测试 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: "/"

【问题讨论】:

  • MemoryRouter 不应该影响 location.pathname,这就是它的目的。

标签: reactjs testing react-router jestjs


【解决方案1】:

经过更多的尝试和错误,我想出了一些办法。 “/”是初始网址,但我不知道如何更改它。我传递了组件将导航到的 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");
});

【讨论】:

    猜你喜欢
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2021-09-19
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多