无法使用酶在react-router中测试重定向

IT技术 reactjs react-router jestjs enzyme
2021-04-28 10:27:15

我正在尝试使用酶测试我的应用程序中的重定向按钮。

我不确定如何准确地做到这一点,但我假设我只需要对包裹在<Link>. (我将其命名为 takeMeToB)。见下文 :

import React from 'react';
import Enzyme, {mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import {BrowserRouter as Router, Link, MemoryRouter, Route, Switch} from 'react-router-dom';
import {createMemoryHistory} from "history";

Enzyme.configure({adapter: new Adapter()});

const history = createMemoryHistory();

describe('Routing test', () => {
    let wrapper;

    beforeEach(() => {
        wrapper = mount(
            <MemoryRouter history={history} initialEntries={['/A']}>
                    <div className={"Test"}>This is my Test Component and should not have any test specific code in it
                        <Router>
                            <Switch>
                                <Route path={"/A"}>
                                    <div className={"A"}>A</div>
                                    <Link to={"/B"}>
                                        <button className={"takeMeToB"}>
                                            Take me to B!!
                                        </button>
                                    </Link>
                                </Route>
                                <Route path={"/B"}>
                                    <div className={"B"}>B</div>
                                </Route>
                            </Switch>
                        </Router>
                    </div>
                </MemoryRouter>
        );
    });


    it('test redirect', () => {

        expect(wrapper.find(".Test")).toHaveLength(1);

        expect(wrapper.find(".A")).toHaveLength(1);
        expect(wrapper.find(".B")).toHaveLength(0);

        wrapper.find(".takeMeToB").at(0).simulate('click');

        expect(wrapper.find(".A")).toHaveLength(0);
        expect(wrapper.find(".B")).toHaveLength(1);
    });

    afterEach(() => {
        wrapper.unmount();
    });
});

我的测试的第一部分有效。它找到了 A,但没有找到 B。但是点击之后,'B' 路由应该在 DOM 中可见,而不是 A。这就是我的测试失败的地方。

注意:路由器 (BrowserRouter) 在我的__mocks__文件夹中被模拟出来您可以有效地忽略它。

2个回答

看来我需要{ button: 0 }作为酶的论据:

it('matches snapshot', () => {

    expect(wrapper.find(".Test")).toHaveLength(1);

    expect(wrapper.find(".A")).toHaveLength(1);
    expect(wrapper.find(".B")).toHaveLength(0);

    wrapper.find('.takeMeToB').simulate('click', { button: 0 });

    expect(wrapper.find(".A")).toHaveLength(0);
    expect(wrapper.find(".B")).toHaveLength(1);
});

不知道为什么会这样,但我在看一些类似的问题时遇到了它。