首页 > 解决方案 > 函数返回的 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);
});

任何有关如何获得它的帮助将不胜感激。提前致谢。

标签: node.jsmockingjestjs

解决方案


似乎断言没有在正确的变量上完成。

需要断言getLogger

您编写测试用例的第一种方法是正确的。

添加这样的断言:

 expect(getLogger.mock.results[0].value.info).toBeCalledTimes(1);

推荐阅读