如何使用摩卡在reactjs中testing这个asynchronous方法调用

// 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 }) 

我不知道如何使用摩卡testing以上。 代码是调用方法updateBalance被调用,实际上确实发生了抓取API调用,但是testing仍然失败。 如果我同时调用updateBalance(),它会传递…如何让testing等待承诺解决?

你并没有真正说出你想要testing的方法,但是如果你想testing的是这个方法在networking调用中parsing,那么就没有必要使用Sinon或者其他任何方法,因为这就是你需要:

 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(); }); }); 

这将testing该方法的实际工作,但速度慢,不是一个真正的unit testing,因为它依赖于在那里的networking,并在浏览器中运行testing,可以为您提供一个工作实现的fetch 。 在Node中运行它或者如果服务closures,它将会失败。

如果你想testing这个方法实际上做了什么特定的事情,那么你将需要在一个函数传递给你的testing:

  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); }); }); 

如果你想学习如何testing这样的代码,而不依赖于正在调用的networking服务的function链接,你可以看看这个答案中描述的三种不同的技术 。