gpt4 book ai didi

javascript - 检测 console.log() 调用

转载 作者:数据小太阳 更新时间:2023-10-29 04:22:00 27 4
gpt4 key购买 nike

我正在尝试为使用 console.log() 将消息写入 JavaScript 控制台的调试方法编写测试用例。测试必须检查消息是否已成功写入控制台。我正在使用 jQuery。

有没有办法将钩子(Hook)附加到 console.log() 或以其他方式检查消息是否已写入控制台,或关于如何编写测试用例的任何其他建议?

最佳答案

console.log 不会记录已记录的消息,也不会发出您可以监听的任何事件。您的测试不可能直接验证其来自 JavaScript 的输出。相反,您的测试代码需要将 console.log 替换为一个 mock 实现,该实现会跟踪日志消息以供以后验证。

Mocking 是大多数 JavaScript 测试框架都支持的常见功能。例如,the Jest test framework provides a jest.spyOn function用模拟实现替换给定方法,模拟实现记录每次调用的参数 in a .mock property在将它们传递给原始实现之前。每次测试后,您可能想调用 jest.clearAllMocks()为下一次测试重置记录的参数列表,或使用 the equivalent clearMocks: true config option .

function saySomething() {
console.log("Hello World");
}
jest.spyOn(console, 'log');

test("saySomething says hello", () => {
expect(console.log.mock.calls.length).toBe(0);
saySomething();
expect(console.log.mock.calls.length).toBe(1);
expect(console.log.mock.calls[0][0]).toBe("Hello World");
});

afterEach(() => {
jest.clearAllMocks();
});

如果您没有使用测试框架(您可能应该使用),您可以自己创建一个简单的模拟。

function saySomething() {
console.log("Hello World");
}
function testSomething() {
// Replace console.log with stub implementation.
const originalLog = console.log;
const calls = [];
console.log = (...args) => {
calls.push(args);
originalLog(...args);
};

try {
console.assert(calls.length == 0);
saySomething();
console.assert(calls.length == 1);
console.assert(calls[0][0] == "Hello World");
} catch (error) {
console.error(error);
} finally {
// Restore original implementation after testing.
console.log = originalLog;
}
}

关于javascript - 检测 console.log() 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7246884/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com