【问题标题】:How to use Jest to test a console.log that uses chalk?如何使用 Jest 测试使用粉笔的 console.log?
【发布时间】:2021-10-01 09:58:39
【问题描述】:

在我的模块中编写节点 CLI 我有一个 console.logchalk,例如:

console.log(
  chalk.green(`${delta}:`),
  chalk.white(`\nAPI: ${apiPath}`),
)

当我运行 Jest 代码覆盖率 --coverage 时,我被提醒我没有测试所以我写道:

test(`Test console log`, async () => {
  await mod(params)
  await expect(console.log).toBe(`${delta}:\nAPI: ${apiPath}`)
})

但我收到以下错误:

Expected: "string"
Received: [Function log]

我尝试过的研究的第二次尝试:

test(`Test console log`, async () => {
  await mod(params)
  await expect(console.log).toHaveBeenCalledWith(`${delta}:\nAPI: ${apiPath}`)
})

但我收到以下错误:

Received has type:  function
Received has value: [Function log]

研究:

使用 Jest 如何测试使用粉笔的 console.log

【问题讨论】:

    标签: node.js unit-testing jestjs chalk


    【解决方案1】:
    // newTest.js
    
    const chalk = require('chalk');
    
    function functionUnderTest() {
      console.log(chalk.green(`${delta}:`), chalk.white(`\nAPI: ${apiPath}`));
    }
    
    module.exports = functionUnderTest;
    
    
    // newTest.test.js
    
    const functionUnderTest = require('./newTest');
    const chalk = require('chalk');
    
    jest.mock('chalk', () => ({
      green: jest.fn(),
      white: jest.fn(),
    }));
    
    it('calls console.log and chalk.blue with correct arguments', () => {
      const spy = jest.spyOn(global.console, 'log');
      chalk.green.mockReturnValueOnce('test-blue');
      chalk.white.mockReturnValueOnce('test-white');
    
      functionUnderTest(5, 'my-path');
    
      expect(chalk.green).toHaveBeenCalledWith('5:');
      expect(chalk.white).toHaveBeenCalledWith('\nAPI: my-path');
      expect(global.console.log).toHaveBeenCalledWith('test-blue', 'test-white');
    
      spy.mockRestore();
    });
    

    要访问全局对象,您必须使用全局上下文 (Jest: how to mock console when it is used by a third-party-library?)。 您可以通过监视 console 全局对象的 log 方法来做到这一点。

    关于测试本身的重要部分是需要模拟两个依赖项,console.log(在间谍中完成)和chalk(我正在使用jest.mock ) 我说它有一个名为green 的属性,它是一个模拟函数(和white)。这里应该测试的是console.log 打印从chalk.green 调用返回的内容。因此分配了一个虚拟字符串作为chalk.green 调用(test-result)的结果,并断言console.log 是用相同的字符串调用的。 white 模拟函数也是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-07
      • 2012-05-26
      • 2017-11-11
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多