I'm having hard time writing test unit with Jest :/ Here is my code:
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 is always 0. I tried to check how the component looks like after rendering. Asked the question here: (How to see what the rendered React component looks like in the Jest unit test?) The snapshot file says it's null:
exports[`NewRec component returns true if blah blah 1`] = `null`;
So why it's always null? What is the problem in the code? The "NewRec" component is using mixins (mixins: [React.addons.LinkedStateMixin]
). Can that cause the problem?
UPDATE: Here is the component code:
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>
);
}
});