当承诺被拒绝时,如何使react-query控制台错误静音?
我正在测试一个由react-query. 当承诺被拒绝时,我需要测试它的回滚行为。不幸的是,react-query日志使用 拒绝了对控制台的承诺console.error,这弄脏了我的测试输出。如何防止将react-query拒绝的承诺记录为控制台错误?
回答
react-query有一个称为setLogger(曾经被调用setConsole)的方法,您可以使用它来实现这一点。
静音来自 的所有控制台消息react-query:
setLogger({
log: () => {},
warn: () => {},
error: () => {},
});
再次取消静音react-query:
setLogger(window.console);
如果您只想静音某些级别而不静音其他级别,您可以通过设置空功能和window.console功能的任意组合。例如:
setLogger({
log: () => {},
warn: window.console.warn,
error: window.console.error,
});
如果您只想在单个测试中将记录器静音,则可以在相关测试的开始和结束时进行这些调用。
如果您希望将整个测试文件的记录器静音,您可以使用 Jest 的设置和拆卸方法:
beforeAll(() => {
setLogger({
log: () => {},
warn: () => {},
error: () => {},
});
});
afterAll(() => {
setLogger(window.console);
});
如果您希望将套件中所有测试的记录器静音,您可以将调用添加到测试设置文件(例如命名为testSetup.js),然后将以下内容添加到您的 jest 配置中:
setupFilesAfterEnv: ['<rootDir>/testSetup.js'],
我个人创建了一个在我的测试中使用的辅助函数(TypeScript):
export async function withMutedReactQueryLogger(
func: () => Promise<any>
): Promise<any> {
const noop = () => {
// do nothing
};
setLogger({
log: noop,
warn: noop,
error: noop,
});
const result = await func();
setLogger(window.console);
return result;
}
我像这样使用它:
test('test something', async () => {
await withMutedReactQueryLogger(async () => {
// write my test here
})
})