首页 > 解决方案 > 如何模拟“粉笔”库的所有方法?

问题描述

我正在使用粉笔来设置终端文本的样式,并编写了一些辅助函数来返回chalk实例:

/* colorUtils.js */
const chalk = require("chalk");

function redUnderline(text) {
  return chalk.red.underline(text);
}
function greenUnderline(text) {
  return chalk.green.underline(text);
}

module.exports = { redUnderline, greenUnderline };

为了测试上述功能,我使用Jest编写了我的测试套件:

/* colorUtils.test.js */
const chalk = require("chalk");
const { redUnderline, greenUnderline } = require("./colorUtils");

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}));

describe("colorUtils", () => {
  describe("redUnderline", () => {
    it("should return a red, underlined string", () => {
      const result = redUnderline("foo");
      expect(chalk.red.underline).toHaveBeenCalledWith("foo");
    });
  });
  describe("greenUnderline", () => {
    it("should return a green, underlined string", () => {
      const result = greenUnderline("foo");
      expect(chalk.green.underline).toHaveBeenCalledWith("foo");
    });
  });
});

上面的测试套件通过没有问题。

但是,为了测试它chalk.red.underlinechalk.green.underline正确调用,我需要chalk使用jest.mock()以下代码进行模拟:

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}))

是否有更紧凑的语法jest.mock()可以模拟所有 chalk实例方法成为jest.fn()

我尝试使用以下模拟方法:

jest.mock("chalk");

但是,第一个测试将失败:

    TypeError: Cannot read property 'underline' of undefined

      2 |
      3 | function redUnderline(text) {
    > 4 |   return chalk.red.underline(text);
        |                    ^
      5 | }

标签: javascriptunit-testingjestjschalk

解决方案


推荐阅读