【问题标题】:Error testing React component with Enzyme: 'Invariant Violation: You should not use <Link> outside a <Router>'使用 Enzyme 测试 React 组件时出错:'不变违规:您不应在 <Router> 外使用 <Link>'
【发布时间】:2018-05-26 18:31:02
【问题描述】:

我正在尝试对组件进行简单的“浅层”测试:

class Background extends React.Component{

selectColor = (e) => {
    let bgColor = window.getComputedStyle(e.target)
    .getPropertyValue("background-color");

    this.props.dispatch(actions.set_bg_color(bgColor));
    this.next();
}

next = () => {
    this.props.history.push('/editor');
}

render(){
    return(
        <section className="select-background">
            <Menu />
            <p className="p-select-background">
                Select Background
                <span className="p-background-message">
                    (appears if image is too small to fit screen)
                </span>
            </p>

            <div className="bg-color-palette-container">
                <div className="bg-color-palette-wrapper">
                    <div className="bg-color" onClick={this.selectColor}></div>
                    <div className="bg-color" onClick={this.selectColor}></div>
                    <div className="bg-color" onClick={this.selectColor}></div>
                    <div className="bg-color" onClick={this.selectColor}></div>
                    <div className="bg-color" onClick={this.selectColor}></div>
                    <div className="bg-color" onClick={this.selectColor}></div>
                    <div className="bg-color" onClick={this.selectColor}></div>
                    <div className="bg-color" onClick={this.selectColor}></div>
                </div>
            </div>
        </section>
    )
  }
}

 const mapToState = (state, props) => ({
    bgColor: state.bgColor
})

export default connect(mapToState)(Background);

这是测试:

import React from 'react';
import {shallow} from 'enzyme';
import store from '../store.js';
import Background from './Background';

describe('<Background />', () => {
    it('Renders without crashing', () => {
      shallow(<Background store={store}/>);
      expect(wrapper.hasClass('select-background')).toEqual(true);
    });
});

这会失败,但如果我更改为 .hasClass('') 它会通过。到目前为止,每一步都给我带来了问题,但在这里我找不到任何有效的解决方案。关于这个或更好的测试 React 组件的方法有什么建议吗?

回购链接: https://github.com/matthewmp/memer

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    解决了。必须在浅包装器上使用 .dive()。

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 2020-10-31
      • 1970-01-01
      • 2019-09-16
      • 2015-08-07
      • 2018-03-12
      • 2017-02-27
      • 2019-08-07
      • 2020-02-04
      相关资源
      最近更新 更多