使用酶测试React组件时出错:'不变违规:您不应该使用 在外面 “

问题描述 投票:4回答:1

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

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个回答
2
投票

解决了。不得不在浅包装上使用.dive()。

© www.soinside.com 2019 - 2024. All rights reserved.