使用React Router进行酶集成测试测试-通过链接更新测试组件 [英] Enzyme integration testing testing with react router - testing components update with links

查看:63
本文介绍了使用React Router进行酶集成测试测试-通过链接更新测试组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试单击链接是否可以更新我的应用程序中的组件。

I would like to test that clicking on a link updates the components in my app.

这是我的应用程序,当您单击它时,它会呈现关于组件

Here's my app, when you click on about it renders the About component

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"

我正在使用React Router v4,React 16和酶3.1

I'm using react router v4, react 16 and enzyme 3.1

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

Is it possible to test in this way using React Router and enzyme?

推荐答案

链接的渲染功能将检查 event.button === 0 。这就是为什么如果在没有适当参数的情况下调用 simulate 会使酶检查失败的原因。

Link's render function will check for event.button === 0. That's why check fails with enzyme if you call simulate without proper params.

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

祝你好运。

这篇关于使用React Router进行酶集成测试测试-通过链接更新测试组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆