如何用Jasmine验证一个模块称为具有正确参数的子模块方法

时间:2015-02-08 19:20:59

标签: jasmine

以下测试规范模拟调用将某些内容写入文件系统的模块。在内部,它使用fs来做到这一点。我想确保使用正确的参数调用fs.writeFile()。但是,toHaveBeenCalledWith()似乎不适用于泛型Function参数。关于如何让toHaveBeenCalled与我期望的一起工作的任何想法?

测试规范:

var fs = {
    writeFile: function (arg1, arg2, cb){}
}

var writeContent = {
    toFS: function (){
        var path = "some/calculated/path";
        var content = "some content";
        fs.writeFile(path, content, function(){})
    }
}

describe("writeContent", function() {

    var writeFileSpy = null;

    beforeEach(function() {

        writeFileSpy = jasmine.createSpy('writeFileSpy');
        spyOn(fs, 'writeFile').and.callFake(writeFileSpy);
    });

    it("can call spy with callback", function() {

        writeContent.toFS();

        expect(writeFileSpy).toHaveBeenCalledWith("some/calculated/path", "some content", Function);
    });

});

结果:

  Message:
    Expected spy writeFileSpy to have been called with [ 'some/calculated/path', 'some content', Function ] but actual calls were [ 'some/calculated/path', 'some content', Function ].

1 个答案:

答案 0 :(得分:1)

回答我自己的问题:-)只需要将函数包含在jasmine.any()中,如下所示:

expect(writeFileSpy).toHaveBeenCalledWith("some/calculated/path", "some content", jasmine.any(Function));