首页 > 解决方案 > 运行 Jasmine 测试时如何查看“console.log”的输出

问题描述

我开发了一个 Node.js 模块,我正在使用 Jasmine 为其编写单元测试。该模块用于在使用设置为 trueconsole.log的参数调用时打印出一些信息。verbose

假设模块如下所示:

foo.js

function foo(arg1, verbose){
    var output = "Hello " + arg1;
    if(verbose)console.log("Returning %s", output);
    return output;
}
module.exports = foo;

假设我的测试如下所示:

foo-spec.js

const foo = require("path/to/foo")
describe("Foo suite", () => {

    it( "Expect foo to greet", () => {
        expect(foo("World", true)).toBe("Hello World");
    });
});

jasmine我通过在终端中输入来运行我的测试:

$ jasmine

一切都很好,除了我想看到详细的输出。

$ jasmine
Returning Hello World

有没有办法让 Jasmine 做到这一点?

标签: node.jsjasmineconsole.log

解决方案


好的,我已经找到了解决方法。监视以console.log某种方式修补了它。

foo-spec.js

const foo = require("path/to/foo")
describe("Foo suite", () => {

    it( "Expect foo to greet", () => {

        //This makes the log visible again from the command line.
        spyOn(console, 'log').and.callThrough();

        expect(foo("World", true)).toBe("Hello World");
    });
});

不知道为什么,但是spyOn使日志再次可见。尽管我并没有真正用它做任何事情,除了调用callThrough. 我最好的猜测是,通过这样做,console.log实际上是从 Jasmine 进程中调用的。


推荐阅读