使用Jest测试 - 通过测试功能设置重置/清除变量并捕获控制台日志

时间:2018-01-30 19:40:57

标签: javascript unit-testing jest

我正在学习用Jest写单元测试。

我使用的是打字稿,但这不应该是个问题。随意提供纯JavaScript的示例。

直到现在我还有功能:

const space = String.fromCharCode(0x0020);
const rocket = String.fromCharCode(0xD83D, 0xDE80);
let notified: boolean = false;

export const logHiring = (message: string = "We're hiring!", emoji: string = rocket) => {
    if (!notified) {
        console.info(
            [message, emoji]
                .filter((e) => e)
                .join(space)
        );

        notified = true;
    }
};

是的,函数应该每次初始化只记录一个消息控制台。

并且没有真正工作测试:

import {logHiring} from "../index";

const rocket = String.fromCharCode(0xD83D, 0xDE80);

// First test
test("`logHiring` without arguments", () => {
    let result = logHiring();
    expect(result).toBe(`We're hiring! ${rocket}`);
});

// Second test
test("`logHiring` with custom message", () => {
    let result = logHiring("We are looking for employees");
    expect(result).toBe(`We are looking for employees ${rocket}`);
});

// Third test
test("`logHiring` multiple times without arguments", () => {
    let result = logHiring();
    result = logHiring();
    result = logHiring();
    expect(result).toBe(`We're hiring! ${rocket}`);
});

我有两个问题:

  1. 如何测试控制台日志?我已经尝试spyOn没有成功。
  2. 如何为每个测试重置内部(来自函数)notified变量?

1 个答案:

答案 0 :(得分:1)

  

如何测试控制台日志?我没试过就试过spyOn。

https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname

const spy = jest.spyOn(console, 'log')
logHiring();
expect(spy).toHaveBeenCalledWith("We're hiring!")
  

如何为每个测试重置内部(来自函数)通知变量?

导出类似

的getter / setter函数
// index.js
export const setNotified = (val) => { notified = val }
export const getNotified = _ => notified

// index.test.js
import { getNotified, setNotified } from '..'
let origNotified = getNotified()
beforeAll(_ => {
  setNotified(/* some fake value here */)
  ...
}
afterAll(_ => {
  setNotified(origNotified)
  ...
}