检测console.log()调用 [英] Detecting console.log() calls

查看:236
本文介绍了检测console.log()调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a test case for a debugging method that writes messages to the JavaScript console using console.log(). The test has to check that the message has been successfully written to the console. I'm using jQuery.

是否可以将钩子连接到console.log()或以其他方式检查是否已将消息写入控制台,或者是否有其他有关如何编写测试用例的建议?

Is there a way to attach a hook to console.log() or otherwise check that a message has been written to the console, or any other suggestions on how to write the test case?

推荐答案

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

console.log doesn't keep a record of messages that are logged, or emit any events that you could listen for. It's not possible for your tests to directly verify its output from JavaScript. Instead, your test code will need to replace console.log with a mock implementation that does keep track of log messages for later verification.

模拟是大多数JavaScript测试框架支持的常见功能.例如, Jest测试框架提供了jest.spyOn函数使用模拟实现替换给定方法,该实现记录了每次调用中的参数.mock属性之前,将其传递给原始实现.每次测试后,您可能需要调用 jest.clearAllMocks() 来重置记录下一次测试的参数列表,或使用等效的clearMocks: true配置选项.

Mocking is a common feature supported by most JavaScript test frameworks. For example, the Jest test framework provides a jest.spyOn function which replaces a given method with a mock implementation that records the arguments for each call in a .mock property before passing them on to the original implementation. After each test you may want to call jest.clearAllMocks() to reset the recorded argument lists for the next test, or use 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();
});

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

If you're not using a test framework (you probably should), you can create a simple mock yourself.

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;
  }
}

这篇关于检测console.log()调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆