如何在 if 语句或 try/catch 中测试函数?例如,
export function* onFetchMessages(channel) {
yield put(requestMessages())
const channel_name = channel.payload
try {
const response = yield call(fetch,'/api/messages/'+channel_name)
if(response.ok){
const res = yield response.json();
const date = moment().format('lll');
yield put(receiveMessages(res,channel.payload,date))
}
} catch (error){
yield put(rejectMessages(error))
}
}
我需要输入数据库中实际存在的真实 channel 名称,以便它为后续执行的 yield 返回有效响应,否则会抛出错误。另外,我会收到一条错误消息,无法读取未定义的属性json,因此由于此错误消息,之后的yield无法达到。 所以我的第一个问题是“if(response.ok)”,但即使我删除它,yield response.json()也会返回错误,此外之后的yield也不会被执行。 如果有人能告诉我如何测试这些,我将不胜感激。
最佳答案
将响应对象传递给先前的执行并测试条件,我会这样做,希望这有帮助:
export function* onFetchMessages(channel) {
try {
yield put(requestMessages())
const channel_name = channel.payload
const response = yield call(fetch,'/api/messages/'+channel_name)
if(response.ok){
const res = yield response.json();
const date = moment().format('lll');
yield put(receiveMessages(res,channel.payload,date))
}
} catch (error){
yield put(rejectMessages(error))
}
}
describe('onFetchMessages Saga', () => {
let output = null;
const saga = onFetchMessages(channel); //mock channel somewhere...
it('should put request messages', () => {
output = saga.next().value;
let expected = put(requestMessages()); //make sure you import this dependency
expect(output).toEqual(expected);
});
it('should call fetch...blabla', ()=> {
output = saga.next(channel_name).value; //include channel_name so it is avaiable on the next iteration
let expected = call(fetch,'/api/messages/'+channel_name); //do all the mock you ned for this
expect(output).toEqual(expected);
});
/*here comes you answer*/
it('should take response.ok into the if statemenet', ()=> {
//your json yield is out the redux-saga context so I dont assert it
saga.next(response).value; //same as before, mock it with a ok property, so it is available
output = saga.next(res).value; //assert the put effect
let expected = put(receiveMessages(res,channel.payload,date)); //channel should be mock from previous test
expect(output).toEqual(expected);
});
});
请注意,您的代码可能做了更多我不知道的事情,但这至少应该让您在某些行中解决您的问题。
关于javascript - 在 if 语句中测试 redux-saga 并使用真实值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39428022/