在使用jest测试节点应用程序时,为什么我看不到控制台日志输出

时间:2022-08-29 04:04:12

I am new to testing with jest and I cannot seem to be able to see the console output from modules I want to test.

我是新手测试jest,我似乎无法从我想测试的模块中看到控制台输出。

my-module.js:

var _ = require('underscore');
exports.filter = function(data) {
    if(_.isArray(data)) {
        console.log("Data is: " + data);
        data = data[0];
    }
return data;
}

my-module-test.js:

jest.dontMock('../my-module');

var testdata = [{label: "test"}, {id: 5}];

describe('test my module', function(){
    it('changes some data' , function(){
        var transformedData = require('../my-module').filter(testdata);
        expect(transformedData).toBe(testdata[0]);
    });
});

Why is jest swallowing my console.log output in "my-module.js"?

为什么在“my-module.js”中吞咽我的console.log输出?

1 个解决方案

#1


4  

Jest seems to mock everything by default. Which is the issue I encountered.

Jest似乎默认模拟了一切。这是我遇到的问题。

Underscore "_" was mocked and there was no visible error, so the execution never got to the console.log in the first place.

下划线“_”被模拟并且没有可见的错误,因此执行从未进入console.log。

There are three possibilities (as far as I know) to prevent such a situation:

有三种可能性(据我所知)可以防止出现这种情况:

  1. In your package.json file, prevent mocking of node modules (which includes underscore)

    在package.json文件中,防止模拟节点模块(包括下划线)

    "jest": { "unmockedModulePathPatterns": ["/node_modules/"] }

    “jest”:{“unmockedModulePathPatterns”:[“/ node_modules /”]}

  2. Explicitly prevent auto mocking in your test file using:

    使用以下方法明确阻止测试文件中的自动模拟:

    jest.autoMockOff();

  3. Explicitly exclude underscore from mocking:

    从模拟中明确排除下划线:

    jest.unmock('underscore');

#1


4  

Jest seems to mock everything by default. Which is the issue I encountered.

Jest似乎默认模拟了一切。这是我遇到的问题。

Underscore "_" was mocked and there was no visible error, so the execution never got to the console.log in the first place.

下划线“_”被模拟并且没有可见的错误,因此执行从未进入console.log。

There are three possibilities (as far as I know) to prevent such a situation:

有三种可能性(据我所知)可以防止出现这种情况:

  1. In your package.json file, prevent mocking of node modules (which includes underscore)

    在package.json文件中,防止模拟节点模块(包括下划线)

    "jest": { "unmockedModulePathPatterns": ["/node_modules/"] }

    “jest”:{“unmockedModulePathPatterns”:[“/ node_modules /”]}

  2. Explicitly prevent auto mocking in your test file using:

    使用以下方法明确阻止测试文件中的自动模拟:

    jest.autoMockOff();

  3. Explicitly exclude underscore from mocking:

    从模拟中明确排除下划线:

    jest.unmock('underscore');