// 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 方法,并且 fetch api 调用实际上确实发生了,但测试仍然失败。如果我同步调用 updateBalance() ,它就会通过...我如何告诉测试等待 promise 解决?
最佳答案
你并没有真正说出你想要测试什么 方法确实如此,但如果您想要测试的只是该方法在网络调用上解析,那么就不需要 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();
});
});
这将测试该方法是否确实有效,但它很慢并且不是真正的单元测试,因为它依赖于那里的网络并且您在浏览器中运行测试,该浏览器可以为您提供以下内容的工作实现获取
。一旦在 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 。
关于node.js - 如何使用 mocha 在 ReactJS 中测试此异步方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44585033/