2016-12-02 19 views
5

我正在使用摩卡,酶和期待我的測試。我在組件中有一個函數,它運行另一個函數,它返回一個promise,我不知道如何在運行第二個函數之前測試第一個函數的行爲,然後測試promise(在.then之後獲取錯誤)React與酶的異步,並期待

1功能:

handleUpdateInput (value) { 
    const { access, onUpdateInput } = this.props 
    const v = !value || typeof value === 'string' ? value : access(value) 
    if (onUpdateInput) { 
     onUpdateInput(value ? v : '') 
    } 

    this.setState({ 
     searchText: value 
    }) 

    this.dataSourceUpdate(value) 
} 

第2個功能:

dataSourceUpdate (value) { 
    const { promise, access } = this.props 

    if (value === '') { 
     this.autoCompleteData = [] 
     this.setState({ dataSource: [] }) 
    } else { 
     promise(value) 
     .then(res => { 
      this.autoCompleteData = res.data 
      this.setState({ 
      dataSource: this.autoCompleteData.map(access).slice(0, getMenuItemNumber(this.refs.customAutoComplete)) 
      }) 
     }) 
     .catch(() => { 
      this.autoCompleteData = [] 
      this.setState({ dataSource: [] }) 
     }) 
    } 
    } 

我還希望給我測試異步功能的一個很好的教程使用這些工具:)

回答

0

既然你得到了道具的承諾(這是一個很好的想法),你可以使用sinon嘲笑你的承諾。

例如,你可以嘗試:

var Promise = require('bluebird'); // you can use any Promise module here 

var deferred = Promise.defer(); 
stub = sinon.stub(deferred, 'resolve').returns(deferred.promise); 

deferred.resolve({res: { data: 'YOUR_DATA' }}); 
// or 
deferred.reject(new Error('fake error'));