我很难用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`;
那为什么它总是空的?代码中有什么问题? &#34; NewRec&#34;组件正在使用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>
);
}
});
答案 0 :(得分:0)
我认为 component.find('new-rec').length
为0,因为没有new-rec
组件,标签或您正在寻找的任何内容,我的意思是,我看到此代码const p = component.find('new-rec');
我知道您正在尝试使用 new-rec 类或类似的东西获取 p 标记,但如果您正在寻找课程,然后你必须在de word(css选择器)之前做const p = component.find('.new-rec');
注意de dot。但同样它会为0,因为我在 NewRec 组件中看不到任何带有 .new-rec 类的 p 标记。