【问题标题】:How to test `NavLink` with Mocha from react-router-dom如何使用来自 react-router-dom 的 Mocha 测试“NavLink”
【发布时间】:2017-04-09 21:36:15
【问题描述】:

我想测试一下我的NavLink是否有某个网址:

Splash.js

import React from 'react';
import { NavLink } from 'react-router-dom'
import Logo from '../shared/logo/index';
import * as styles from './style.css';

class Splash extends React.Component {
  render(){
    return (
      <div className={styles.indexAppContent}>
        <NavLink to="/home"  className={styles.index}>
          <Logo />
        </NavLink>
      </div>
    );
  }
}

export default Splash;

测试

/* eslint-disable object-property-newline */
import React from 'react';
import ReactTestUtils from 'react-dom/test-utils'
import { expect } from 'chai';
import { NavLink } from 'react-router-dom'
import { shallow } from 'enzyme';


describe('<Splash />', () => {

  it('Logo links to home', () => {
    expect(wrapperNavLink.prop('to'))
      .equals('/home');
  })

});

如何测试渲染的 href 的值以进行反应?

【问题讨论】:

    标签: javascript reactjs testing mocha.js enzyme


    【解决方案1】:

    有两种方法可以测试传递道具是否正确到达您的组件。

    1.独立测试组件-

    import React from 'react';
    import { expect } from 'chai';
    import { shallow, mount, render } from 'enzyme';
    import { NavLink } from 'react-router-dom';
    
    describe("<NavLink  />", () => {
        it("1.contains correct passed prop", () => {
            const comp = (
                <NavLink to="/home"  className={"test"}>
                    NaveLink Test
                </NavLink>
            );
            const wrapper = shallow( comp );
            expect(wrapper.instance().props.to).to.equal("/home");
        });
    });
    

    2.测试整个组件,例如组件&lt;Splash /&gt;在您的情况下。

    import React from 'react';
    import { expect } from 'chai';
    import { shallow, mount, render } from 'enzyme';
    import { NavLink } from 'react-router-dom';
    import Splash from './splash'; // <----------- import the component you want to test
    
    describe("<Splash  />", () => {
        it("2.contains correct passed prop", () => {
            const comp = (
                <Splash />
            );
            const wrapper = shallow( comp );
    
            expect(wrapper.find(NavLink).first().props().to).to.equal("/home");
        });
    });
    

    【讨论】:

    • 谢谢伙计,我花了一段时间才回到这个:) 那很有趣。 wrapper.find(NavLink).first().props().to 所以你通过传递实际的 component 来使用 find ,谢谢芽。有没有我错过的明确文档?
    • @JamieHutber 欢迎您。我认为您可以查看 airbnb 酶文档,
    • 我收到一个错误 Invariant failed: You should not use outside a
    猜你喜欢
    • 2021-10-20
    • 2022-07-10
    • 2022-08-13
    • 2018-08-23
    • 2018-12-15
    • 2020-10-08
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多