如何在像函数sinon这样的类中存根函数

问题描述 投票:0回答:1
//foldercontroller.js file

// Self invoking function.
(function()
{
    ....
    lib.FolderController = FolderController;

    function FolderController(thePath)
    {
         .... // Some other initializations and other functions
        this.getFileList = getFileList;
        function getFileList()
        {
            return someArray;
        }
    }


})();

我想在下面的代码中存储上面的getFileList函数。我正在使用sinon库。我做了一些事情,但我没有希望

// FileCacheTest.js file Here I want to test some feature

var fileList = ["a","b","c"];
var filesStub = sinon.stub(lib.FolderController, "getFileList")
                     .callsFake(function fakeFn(){
                           return fileList;
                     });

我得到了这个结果:

TypeError:尝试将未定义属性getFileList包装为函数

用例如下。我想在调用folderController.getFileList();时获取我想要的fileList

var folderController = new lib.FolderController(theDirectory);

var files = folderController.getFileList();

我的问题是如何存根这个getFileList函数?

javascript unit-testing sinon
1个回答
0
投票

你的lib.FolderControlleris是一个功能。在这个函数里面你有一个属性getFileList,它也是一个函数。

所以你能做的是:

1)实例化您的对象而不是将其分配给函数:

lib.FolderController = new FolderController('mypath');

2)尝试以这种方式存根:

var filesStub = sinon.stub(lib.FolderController(), "getFileList")
                     .callsFake(function fakeFn(){
                           return fileList;
                     });

但是请记住在return this;函数的末尾添加FolderController,否则它将不会返回一个对象,并且您不能在非对象上存根方法。

我不知道你在做什么,所以检查一个更符合你需求的那个。

© www.soinside.com 2019 - 2024. All rights reserved.