我用玩笑框架测试传奇。当我引发新的错误时,我想测试代码,但是我遇到了问题。
传奇功能
try {
const clientId = yield select(selectClientId)
if (!clientId) {
throw new Error('Client id is not exists')
}
const response = yield call(fetcher, {options})
yield put(clientReceiveData({ data: response }))
} catch (err) {
yield put(clientRequestDataFailure())
}
}
这是一个测试传奇
describe('client fetch data', () => {
const gen = cloneableGenerator(clientDataFetch)(params)
expect(gen.next().value).toEqual(select(selectClientId))
// @ts-ignore
expect(gen.throw(new Error('Client id is not exists')).value).toEqual( put(clientRequestDataFailure()))
// Here expect(received) is undefined
expect(gen.next().value).toEqual(call(fetcher, {options}))
})
未收到与调用提取程序相等的信息
答案 0 :(得分:0)
您已经完成了生成器?,不再需要执行任何代码,断言的方式是: :
expect(gen.next()).toStrictEqual({ done: true, value: undefined })
但是,对于整洁的代码,您要做要预见未定义客户端ID的情况,并且已经正确处理了该情况,因此这不是意外的异常,请尝试:
// generator.ts
function* clientDataFetch(params) {
//...
const clientId = yield select(selectClientId)
if (!clientId) {
yield put(clientRequestDataFailure())
} else {
const response = yield call(fetcher, {options})
yield put(clientReceiveData({ data: response }))
}
}
// test.ts
describe('client fetch data', () => {
const gen = cloneableGenerator(clientDataFetch)(params)
expect(gen.next().value).toEqual(select(selectClientId))
// just return the falsy value
expect(gen.next(undefined).value).toEqual(put(clientRequestDataFailure()))
expect(gen.next()).toStrictEqual({ done: true, value: undefined })
})