函数返回的开玩笑的模拟值

时间:2020-06-16 15:07:25

标签: node.js mocking jestjs

我有一个下面的记录器文件,该文件实现了记录功能。 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);
});

任何有关如何获得它的帮助将不胜感激。预先感谢。

1 个答案:

答案 0 :(得分:0)

似乎没有对适当的变量进行断言。

需要在getLogger上断言

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

添加这样的断言:

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