【问题标题】:Enzyme integration testing testing with react router - testing components update with links使用反应路由器进行酶集成测试测试 - 使用链接更新测试组件
【发布时间】:2018-03-20 22:29:37
【问题描述】:

我想测试点击链接会更新我的应用程序中的组件。

这是我的应用,当你点击 about 时会呈现 About 组件

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

是否可以使用 React Router 和酶以这种方式进行测试?

【问题讨论】:

    标签: javascript reactjs testing react-router enzyme


    【解决方案1】:

    链接的render function 将检查event.button === 0。这就是为什么如果您在没有正确参数的情况下调用 simulate 时使用酶检查失败的原因。

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

    祝你好运。

    【讨论】:

    • 很棒的发现!!很高兴我找到了这个,谢谢@fund 和@Finnnn,之后我做了一些挖掘来发现 button: 0 的含义以及是否可以安全地进行所有事件。查看链接渲染代码,此注释揭示了含义 ``` event.button === 0 && // 忽略右键单击```。因此,对于我的测试,我将在任何地方使用此修复程序,因为我不关心右键单击。另外仅供参考,关于为什么它不是默认值的酶讨论...github.com/airbnb/enzyme/issues/516
    猜你喜欢
    • 1970-01-01
    • 2017-05-22
    • 2017-08-16
    • 2018-07-22
    • 2019-01-30
    • 2020-08-11
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多