运行 Jasmine 测试时如何查看 `console.log` 的输出

How to see output of `console.log` when running Jasmine tests

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

假设模块如下所示:

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 做到这一点?

好的,我已经找到了解决方法。监视 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 进程中调用的。