[英]Test a React Component Mount with Jest
我試圖找出如何在通過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 (
<Resource raw={resource} key={index}/>
);
});
return (
<ul>{resources}</ul>
);
}
});
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(<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);
});
});
我得到的錯誤是:“TypeError:無法調用方法'然后'未定義',這是可以理解的,但我怎么能糾正這個?
如果你還沒有(你在查看粘貼的代碼時沒有顯示你是否這樣做),那么你需要添加以下兩行中的任何一行。
jest.dontMock('../app/components/resource-list');
要么
jest.dontMock('../path/to/your/apiclient');
默認情況下,Jest會模擬所有必需的模塊依賴項,這將使您的API客戶端始終為任何調用的方法返回undefined。
其次,我想推動您使用您的API處理程序的實際實現,並使用像nock這樣的模塊來模擬HTTP調用。 nock返回的作用域將攔截所有HTTP調用,並讓您對響應有所期望,因此在安裝組件時,您可以讓nock實際返回有效數據並期望一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.