2017-06-16 54 views
2
// Balance.jsx 
... 

updateToken() { 
    const parseResponse = (response) => { 
    if (response.ok) { 
     return response.json() 
    } else { 
     throw new Error('Could not retrieve access token.') 
    } 
    } 

    const update = (data) => { 
    if (data.token) { 
     this.data.accessTokenData = data 
    } else { 
     throw new Error('Invalid response from token api') 
    } 
    } 

    if (this.props.balanceEndpoint !== null) { 
    return fetch(this.props.accessTokenEndpoint, { 
     method: 'get', 
     credentials: 'include' 
    }) 
    .then(parseResponse) 
    .then(update) 
    .catch((err) => Promise.reject(err)) 
    } 
} 

componentDidMount() { 
    this.updateToken() 
    .then(() => this.updateBalance()) 
    } 
} 

// Test 

it('updates the balance',() => { 
    subject = mount(<Balance {...props} />) 
    expect(fetchMock.called('balance.json')).to.be.true 
}) 

我無法弄清楚如何使用Mocha測試上述內容。代碼是調用方法updateBalance並且提取api調用確實發生,但測試仍然失敗。如果我同步調用updateBalance(),它會傳遞...如何讓測試等待承諾解決?如何使用摩卡在reactjs中測試此異步方法調用

+0

你能提供'updateToken'代碼嗎? –

+0

總是'返回'承諾從每個功能。這樣你就可以輕鬆地等待它。 – Bergi

+0

我已經添加了updateToken代碼。 我相信我從updateToken方法返回一個承諾,因爲fetch api返回一個承諾,我直接返回該承諾。我想我已經把它設置成正常工作,我只是不知道如何讓摩卡等待它... – Riina

回答

0

你真的不說你想要什麼來測試該 方法做,但如果你要測試的是,該方法解決了在網絡電話,那麼就沒有必要興農或任何的是,因爲這是所有你需要:

describe("BalanceComponent",() => { 
    it("should resolve the promise on a successful network call",() => { 
     const component = new BalanceComponent({any: 'props', foo: 'bar'}); 

     // assumes you call a network service that returns a 
     // successful response of course ... 
     return component.updateToken();  
    }); 
}); 

這將測試該方法的實際工作,但它是緩慢的,不是真正的單元測試,因爲它依賴網絡在那裏,並且您運行在瀏覽器中進行測試,可以爲您提供fetch的工作實現。在Node中運行它或服務停止時,它將會失敗。

如果你想測試方法實際上做一些具體的事情,那麼你就需要到的是,在您的測試傳遞給then功能:

it("should change the token on a successful network call",() => { 
     const component = new BalanceComponent({any: 'props', foo: 'bar'}); 
     const oldToken = component.data.accessTokenData; 

     return component.updateToken().then(()=> { 
      assert(oldToken !== component.data.accessTokenData); 
     }); 
    }); 

如果您想了解如何測試代碼像這樣,而不依賴於你正在呼叫的網絡服務的功能鏈接,你可以查看three different techniques described in this answer

相關問題