我正在用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}`);
});


我有两个问题:


如何测试控制台日志?我试过spyOn没有成功。
如何为每个测试重置内部(来自功能)notified变量?

最佳答案

如何测试控制台日志?我尝试了不成功的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)
  ...
}

关于javascript - 使用Jest进行测试-重置/清除由测试功能设置的变量并捕获控制台日志,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48529320/

10-12 00:31
查看更多