gpt4 book ai didi

javascript - 使用 Jest 进行测试 - 重置/清除由测试函数设置的变量并捕获控制台日志

转载 作者:行者123 更新时间:2023-12-03 02:36:07 24 4
gpt4 key购买 nike

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

我使用 typescript ,但这里应该不是问题。请随意提供纯 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 变量?

最佳答案

How can I test console logs? I've tried spyOn without succes.

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!")

How can I reset internal (from function) notified variable for each test?

导出 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com