我正在试图弄清楚如何通过mount上的ajax加载初始数据时测试react组件 .
var ResourceList = React.createClass({
componentDidMount: function() {
api.fetchResources(this.props.type).then(function(raw) {
console.log(raw);
this.setState({
resources: raw
});
}.bind(this));
},
getInitialState: function() {
return {
resources: []
};
},
render: function() {
var resources = this.state.resources.map(function(resource, index) {
return (
);
});
return (
- {resources}
);
}
});
componentDidMount 函数调用返回jquery promise的API .
var fetchResources = function(type) {
var endpoint = '/resources';
return $.ajax({
url: base + endpoint + '/' + type,
dataType: 'json',
headers: headers
});
}
// Return promise
module.exports = {
fetchResources: fetchResources
};
我的测试代码如下所示:
describe('something', function() {
beforeEach(function() {
React = require('react/addons');
TestUtils = React.addons.TestUtils;
ResourceListComponent = require('../app/components/resource-list');
ResourceList = TestUtils.renderIntoDocument();
// Dummy data from server
resources = [{
author: 'author',
body: 'body'
}];
// Add the dummy data from the server
ResourceList.setState({
resources: resources
});
});
it('1', function() {
expect(ResourceList.state.resources.length).toBe(1);
});
});
我得到的错误是:“TypeError:无法调用方法'然后'未定义',这是可以理解的,但我怎么能纠正这个?