node.js - 函数返回的 Jest 模拟值
问题描述
我有一个如下的记录器文件,它实现了记录功能。uuidLogger.js
const winston = require('winston'),
CustomTransport = require('./customTransport');
function getLogger(route) {
return winston.createLogger({
defaultMeta: { route },
transports: [new CustomTransport()]
});
}
module.exports = getLogger;
它由这样的函数导入并用于记录testfn.js
const uuidLogger = require('./uuidLogger')('test-fn');
function testMock() {
uuidLogger.info('Hey I am just logging');
}
module.exports = { testMock };
我正在尝试在 testfn.js 中模拟 uuidlogger,以便我可以跟踪在 uuidLogger 对象上调用的各种方法。我尝试了以下方法。
import { testMock } from './testfn';
import getLogger from './uuidLogger';
const logger = getLogger('testfn');
jest.mock('./uuidLogger', () =>
jest.fn(() => ({
info: jest.fn(() => console.log('Mocked function actually called'))
}))
);
it('verify that info method was called on returned object', () => {
testMock('abx');
expect(logger.info).toBeCalledTimes(1);
});
它能够模拟调用的方法,但是模拟信息没有反映在 logger.info 对象中。
我也尝试了以下方法
import { testMock } from './testfn';
import getLogger from './uuidLogger';
jest.mock('./uuidLogger', () =>
jest.fn(() => ({ info: jest.fn(() => console.log('Top level fn')) }))
);
const logger = {
error: jest.fn(),
info: jest.fn(() => {
console.log('Overwritten fn');
})
};
getLogger.mockReturnValue(logger);
it('shud return Winston instance', () => {
testMock('abx');
expect(logger.info).toBeCalledTimes(1);
});
任何有关如何获得它的帮助将不胜感激。提前致谢。
解决方案
似乎断言没有在正确的变量上完成。
需要断言getLogger
您编写测试用例的第一种方法是正确的。
添加这样的断言:
expect(getLogger.mock.results[0].value.info).toBeCalledTimes(1);
推荐阅读
- c# - 如何找到从通用接口派生的非通用接口?
- python - 如何使用自定义参数保存/加载 tensorflow 2.3.1 序列化模型(DoubleDuelingDQN Agent)?
- amazon-web-services - CloudWatch 成本 - 数据处理
- javascript - 如何在反应中将段落中存在的双“OO”字变成绿色方块?例如 clooney - cl[绿色方块]ey
- innodb - 一个 galera 节点出现故障并开始将错误 innodb 报告为未知或不受支持的引擎
- tensorflow - ValueError:找不到内置操作码“RESIZE_BILINEAR”版本“3”的操作注册失败
- javascript - 当我尝试在我的 react.js 组件中迭代对象数组时,为什么会出现错误?
- python - Python,从时间序列中提取特征(TSFRESH 包或我可以使用什么?)
- android - 如何在 Android 中同时为 ImageFlipper 实现 OnClick 和 Sliding 事件
- php - 如何在 lumen 7.0 中配置存储