我正在使用Jest为一些Redux操作实现单元测试。
但是,出于某种原因,这个测试用例永远不会失败。
该操作的摘要版本如下所示:
export function attachFile(file) {
return (dispatch, getState) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
dispatch({
type: actionTypes.ATTACH_FILE_DONE,
file: {
content: reader.result,
size: file.size,
mimeType: file.type,
name: file.name,
},
});
resolve();
};
reader.onerror = (error) => {
const errorMessage = `Error reading file: ${file.name}: ${error}`;
dispatch({
type: actionTypes.ATTACH_FILE_FAIL,
errorMessage,
});
reject(errorMessage);
};
reader.readAsDataURL(file);
});
};
}
测试它的jest代码:
store.dispatch(attachFile(file)).then(() => {
console.log('ACTUAL ACTIONS:', store.getActions());
console.log('EXPECTED ACTIONS:', expectedActions);
expect(store.getActions()).toEqual(expectedActions);
})
记录信息显示值不相等,但 Jest 始终通过此测试。 我甚至尝试添加
fail('Just fail')
但是测试仍然通过,即使数据完全不同或强制失败。
我环顾四周看到了类似的代码,但我发现我的代码没有任何有意义的差异,例如this one
我还注释掉了Promise中的所有代码,并强迫它在测试代码上失败......仍然通过。
知道可能出现什么问题吗?
答案 0 :(得分:2)
一旦代码完成执行,就会认为测试已完成。
你需要告诉Jest等到你的承诺得到满足。
你可以通过将一个参数(让我们称之为done
)传递给你的test|it
函数来做到这一点,这样,Jest将等到done
被调用。< / p>
所以基本上是这样的:
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
对于您的示例,请在done
:
except
{
...
expect(store.getActions()).toEqual(expectedActions);
done();
}