【问题标题】:Rendering a React component in Jest returns null在 Jest 中渲染 React 组件返回 null
【发布时间】:2016-11-14 19:31:57
【问题描述】:

我很难用 Jest 编写测试单元:/ 这是我的代码:

import { NewRec } from '../src/components/edit';
import { shallow } from 'enzyme';
import React from 'react/lib/ReactWithAddons';

jest.mock('react-dom');
jest.mock('react/lib/ReactDefaultInjection');

describe('NewRec component', () => {
    const component = shallow(<NewRec />);
    it('returns true if blah blah', ()=>{
         const p = component.find('errortitle');
         expect(p.length).toEqual(1)
    });
});

P 始终为 0。我尝试检查渲染后组件的外观。在这里问这个问题:(How to see what the rendered React component looks like in the Jest unit test?) 快照文件说它是空的:

 exports[`NewRec component returns true if blah blah 1`] = `null`;

那么为什么它总是为空?代码中的问题是什么? “NewRec”组件正在使用 mixins (mixins: [React.addons.LinkedStateMixin])。这会导致问题吗?

更新:这是组件代码:

export const NewRec = React.createClass({
    mixins: [React.addons.LinkedStateMixin],

    getInitialState() {
        return {
            group_id: null,
            title: "",
            errors: {},
        }
    },

    createRec(event) {
        event.preventDefault();
        if (!this.state.title.length) {
            this.setError('title', "Please add a title");
            return;
        }
        if (!this.state.group_id) {
            this.setError('group', "Please select a group");
            return;
        }
        serverCache.createRec(
            { group: this.state.group_id, title: this.state.title },
            rec => { browser.gotoRec(rec.id); }
        );
    },

    selectgroup(group_id) {
        this.setState({group_id: group_id});
    },

    rendergroupList(groups) {
        return (
                <div > { groups.map(this.rendergroup) } </div>
        );
    },

    onTitleChange(event) {
        this.setState({title:event.target.value});
    },

    componentWillMount() {
        const user = serverCache.getUser();
        if (!user || !user.get('name')) {
            notifications.warning('Please login first.');
        }
    },

    render() {
        const user = serverCache.getUser();
        const groups = serverCache.getgroups();

        return (
            <div className="row">
                <form className="form-horizontal" onSubmit={this.createRec}>
                    <label htmlFor="title" className="col-sm-3 control-label"> Title </label>
                    <div>
                        <input type="text"  id='title' value={this.state.title} onChange={this.onTitleChange} />
                    </div>
                    <div> 
                        <label htmlFor="group" className="col-sm-3 control-label" >group </label>
                    </div>
                    <div> 
                        {this.state.errors.title ? <div id='errortitle' >{this.state.errors.title} </div>: false }
                        {this.state.errors.group ? <div id='errorgroup' >{this.state.errors.group} </div> : false }
                        <div > 
                            <button type="submit" className="btn btn-primary btn-default btn-block"> Create Rec</button>
                        </div>
                    </div>
                </form>
            </div>
        );
    }
});

【问题讨论】:

  • 能否贴出你的组件代码,或者至少是组件的渲染方法。您还应该注意,shallow 不会触发组件的任何生命周期方法。
  • 看起来很奇怪,也许您应该开始调试,将console.log 添加到渲染方法以检查它们是否被调用。并删除 2 个jest.mock 语句,因为它们不是必需的,并且可能会产生一些奇怪的副作用。
  • 这玩意怎么样?它只使用酶。

标签: javascript unit-testing reactjs jestjs enzyme


【解决方案1】:

我认为 component.find('new-rec').length 为 0,因为没有 new-rec 组件、标签或您要查找的任何内容,我的意思是,当我看到此代码时 const p = component.find('new-rec'); 我明白您正在尝试使用 new-rec 类或类似的东西获取 p 标签,但如果您正在寻找一个类,那么您必须这样做 const p = component.find('.new-rec'); 注意 de 单词前的点(css 选择器)。但它还是 0,因为我在 NewRec 组件中看不到任何带有 .new-rec 类的 p 标记。 p>

【讨论】:

  • 很好的佩德罗。这是我之前的尝试:-P 刚刚更新了代码。所以我想做的是找到具有 id='errortitle'&lt;div&gt; 。可能吗? component.find() 可以查找带有 id 的标签还是只能查找 css 类?
  • @Sarah,是的,你可以通过任何你想要的 CSS 选择器 找到,查看文档github.com/airbnb/enzyme/blob/master/docs/api/ReactWrapper/… 在你的情况下,我认为你可以做到const p = component.find('#errortitle'); 让我知道它是否适合你:)
  • 不,它没有帮助:(问题是这个组件似乎是空的:component = shallow(&lt;NewRec /&gt;);。它不会呈现NewRec。当我尝试使用mount而不是shallow 我得到这个错误:TypeError: Cannot read property monitorScrollValue of null。或者如果我尝试使用 render 而不是 shallow 它会抱怨 componentWillMountNewRec 定义中使用。有没有其他方法来渲染组件来测试它?!
猜你喜欢
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 2018-09-15
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多