[英]Testing async method with mocha and chai
Hi guys I'm having troubles to test an async function with a fetch to a server inside. 嗨,大家好,我很难通过读取内部服务器来测试异步功能。 I'm using mocha with chai-as-promised. 我正在按照承诺的方式使用摩卡咖啡。 The test that is failing is: 'return proper title' I guess I would have to mock the fetch call or something, or maybe the problem is that I'm calling an async function, and as I'm executing a unit test and I don't resolve the promise. 失败的测试是:“返回专有名称”我想我将不得不模拟fetch调用之类的东西,或者问题可能是我在调用异步函数,并且在执行单元测试时不要兑现诺言。 I'm not pretty sure how to achieve that. 我不太确定如何实现这一目标。 Could you help me? 你可以帮帮我吗?
The function to test is: 要测试的功能是:
import React from 'react'
import Technologies from './Technologies'
import fetch from '../../core/fetch'
let title= 'Technologies'
export default {
path: '/technologies',
async action () {
const resp = await fetch('/graphql', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: '{technologies{name,icon,url}}',
}),
credentials: 'include',
})
let { data, } = await resp.json()
if (!data || !data.technologies) throw new Error('Failed to load technologies.')
return {
title:title,
component: <Technologies title={title} technologies={data.technologies} />,
}
},
}
And my tests: 我的测试:
describe('Route', () => {
it('has right path', () => {
expect(Route.path === '/technologies').to.be.true
})
it('return proper title', () => {
const title = 'Technologies'
expect(Route.action().title === title).to.be.true
})
})
try with: 尝试:
describe('Route', () => {
it('has right path', () => {
return expect(Route.path === '/technologies').to.be.true
})
it('return proper title', () => {
const title = 'Technologies'
return expect(Route.action().title === title).to.be.true
})
})
The first strategy suggested in the mocha documentation is using the 'done' callback. Mocha文档中建议的第一个策略是使用“完成”回调。 This is an extra argument to the callback in the it . 这是it中回调的一个额外参数。 You call it after the last assertion in your test. 您在测试中的最后一个断言之后调用它。
for example, for your test you have forget to return the function in expect : 例如,对于您的测试,您忘记了返回Expect中的函数:
describe('Route', () => {
it('has right path', (done) => {
return expect(Route.path === '/technologies').to.be.true
done();
})
it('return proper title', (done) => {
const title = 'Technologies'
return expect(Route.action().title === title).to.be.true
done();
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.