2015-09-07 56 views
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); 
    }); 
}); 

我得到的錯誤是:「類型錯誤:無法調用‘然後’未定義」,這是可以理解的,但我怎麼能糾正這個?

回答

1

如果您還沒有(如果您在查看粘貼的代碼時沒有顯示,那麼您需要添加下面兩行中的任意一行)。

jest.dontMock('../app/components/resource-list'); 

jest.dontMock('../path/to/your/apiclient'); 

玩笑默認情況下,這將有您的API客戶端始終對所調用方法返回undefined嘲笑所有所需模塊的依賴的。其次,我想推動你使用你的API處理程序的實際實現,並使用像nock這樣的模塊模擬​​出HTTP調用。 由nock返回的範圍將攔截所有的HTTP調用,並讓你對響應進行期望,所以在安裝組件時,你可以讓nock實際返回有效數據並期望一切正常。