【问题标题】:Enzyme/React/Redux - Invariant Violation.Enzyme/React/Redux - 不变违规。
【发布时间】:2017-02-27 11:10:13
【问题描述】:

有一些我在没有单元测试的情况下编写的遗留代码(我知道,我知道,糟糕的工程师,没有 cookie),但我们很着急,确实需要网站在几天内上线。

现在我正在努力偿还技术债务。大部分都很简单,但我仍然需要测试反应组件。尝试使用 JSDom 和酶这样做,但经常得到这个错误:

不变违规:在上下文中找不到“商店”或 “连接(谢谢)”的道具。要么将根组件包装在 , 或明确地将“商店”作为道具传递给 “连接(谢谢)”。

所以我的问题是:是什么导致了这个错误,我应该如何解决这个问题?我敢肯定我会有更多问题,但这是目前最大的障碍。

所以,这是测试的设置:

import React from 'react';
import chai from 'chai';
const expect = chai.expect;
import { shallow, mount } from 'enzyme';

import ThankYou from '../src/frontend/js/containers/ThankYou';

describe('<ThankYou />', () => {
  it('is trying to get React testing to work', () => {
    const wrapper = shallow(<ThankYou />);
    //(I know this test *will* fail, but it's failing in the wrong way.)
    expect(wrapper).to.eql({}); 
  });
});

这是组件本身。

class ThankYou extends Component {
  constructor(props){
    super(props);
  }

  render () {
    return (
      <Paper zDepth={1} >
        <div>
          {thankYou.map((pgraph, i) => (<div key={"pg" + i}>
            {pgraph[this.props.language]}
          </div>))}
        </div>
        <Social />
      </Paper>
    );
  }
}

// reduxify is a library I wrote which maps 
// state, actions, and dispatch to props. 
// source: https://github.com/brianboyko/reduxify/blob/master/reduxify.js
export default reduxify(actions, ['language'], ThankYou);

【问题讨论】:

    标签: unit-testing reactjs mocha.js redux enzyme


    【解决方案1】:

    您正在将 reduxify 中包装的类导入到您的测试中。该组件希望通过上下文传递 redux store,因此您看到的错误是警告您情况并非如此。

    您可以模拟 context 以提供一个虚拟存储,或者在没有 reduxify 包装器的情况下导入组件并测试该组件:

    // Export the class before it becomes wrapped
    export class ThankYou extends Component {
      ...
    }
    
    export default reduxify(actions, ['language'], ThankYou);
    
    
    // Update the test to import the basic class
    import { ThankYou } from '../src/frontend/js/containers/ThankYou';
    
    describe('<ThankYou />', () => {
      it('is trying to get React testing to work', () => {
        const wrapper = shallow(<ThankYou />);
        expect(wrapper).to.eql({}); 
      });
    });
    

    希望这会有所帮助。

    【讨论】:

    • 是的,就是这样,我不敢相信我自己没有想到这一点。实际上,我现在确实记得在想这件事,但就在我上床睡觉之前,直到你提醒我这件事才忘记它。可能信息太多,但谢谢!
    猜你喜欢
    • 2018-07-07
    • 2018-03-14
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2016-06-10
    相关资源
    最近更新 更多