与酶集成测试测试反应路由器 - 测试组件的链接更新(Enzyme integration testi

2019-10-28 12:32发布

我想测试点击一个链接在我的应用程序更新组件。

这里是我的应用程序,当你点击它呈现关于组件

import React, { Component } from 'react';
import './App.css';
import {
  MemoryRouter as Router,
  Route,
  Link
} from 'react-router-dom'


const Home = () => <h1>home</h1>
const About = () => <h1>about</h1>

class App extends Component {
  render() {
    return (
      <Router>
        <ul>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/">Home</Link></li>
        </ul>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Router>
    );
  }
}

export default App;

下面是我的测试:

import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';
import { mount } from "enzyme";
import { MemoryRouter} from 'react-router-dom'
import App from './App';

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


// this test passes as expected
it('renders intitial heading as home', () => {
  const wrapper = mount(
    <App />
  );

  const pageHeading = wrapper.find("h1").first().text()
  expect(pageHeading).toEqual('home');
});

it('renders about heading when we navigate to about', () => {
  const wrapper = mount(
    <App />
  );

  const link = wrapper.find("Link").first();
  link.simulate('click');

  const pageHeading = wrapper.find("h1").first().text()
  expect(pageHeading).toEqual('about');
});

第二次测试失败:

FAIL  src/App.test.js
  ● renders about heading when we navigate to about

    expect(received).toEqual(expected)

    Expected value to equal:
      "about"
    Received:
      "home"

我使用反应路由器V4,反应16和酶3.1

是否有可能在使用路由器做出反应和酶这种方法来测试?

Answer 1:

链接的渲染功能将检查event.button === 0 。 这就是为什么检查失败与酶如果调用simulate没有适当的PARAMS。

尝试link.simulate('click', { button: 0 });

祝好运。



文章来源: Enzyme integration testing testing with react router - testing components update with links