3
我想弄清楚如何測試一個反應組件當初始數據通過ajax在裝載上加載。測試一個反應組件與山峯
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 (
<Resource raw={resource} key={index}/>
);
});
return (
<ul>{resources}</ul>
);
}
});
componentDidMount
函數調用返回jquery承諾的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(<ResourceListComponent />);
// 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);
});
});
我得到的錯誤是:「類型錯誤:無法調用‘然後’未定義」,這是可以理解的,但我怎麼能糾正這個?