Jasmine Karma Array.find不是函数

时间:2016-08-02 13:06:47

标签: jasmine karma-runner

我正在使用Jasmine进行测试,而Karma则是我的测试运行员。

我有一个简单的使用Array.prototype.find()的查找方法失败并出现错误:

  

TypeError:myns.dataList.find不是函数

这表明它无法理解这个功能。我在同一个文件中也有该方法的polyfill,并且在Node上也安装了an es6 shim

使用Chrome 51.0.2704

这就是我正在尝试的:

describe('the description', function() {
    it('should work', function() {

        jasmine.getJSONFixtures().fixturesPath = 'base/path/to/json/';
        myns.dataList = loadJSONFixtures('dataList.json');

        console.log(myns.dataList); /* all ok here, json is loaded */

        var theName = myns.dataList.find(function(entry) {
            return entry.name === selfName;
        });

        expect(2 + 2).not.toEqual(4); /* doesn't get here because of TypeError */
    });
});

注意:这可以直接从浏览器运行Jasmine时使用

1 个答案:

答案 0 :(得分:1)

可能是迟到的回复,但这是您可以采取的措施来解决此问题。在测试代​​码即将调用fin方法之前,请调用以下代码。

    if (typeof Array.prototype.find !== 'function') {
        Array.prototype.find = function(iterator) {
            var list = Object(this);
            var length = list.length >>> 0;
            var thisArg = arguments[1];
            var value;

            for (var i = 0; i < length; i++) {
                value = list[i];
                if (iterator.call(thisArg, value, i, list)) {
                    return value;
                }
            }
            return undefined;    
        };
    }

这将检查数组定义中是否没有这样的方法(find),它将添加一个。

最初发布在此处:http://sehajpal.com/2016/10/missing-function-definitions-in-jasmine-karma-testing-not-a-function/

所以,粗略地说,你的代码看起来像(根据你的需要重构):

describe('the description', function() {
    it('should work', function() {

        jasmine.getJSONFixtures().fixturesPath = 'base/path/to/json/';
        myns.dataList = loadJSONFixtures('dataList.json');

        console.log(myns.dataList); /* all ok here, json is loaded */
        if (typeof Array.prototype.find !== 'function') {
            Array.prototype.find = function(iterator) {
                var list = Object(this);
                var length = list.length >>> 0;
                var thisArg = arguments[1];
                var value;

                for (var i = 0; i < length; i++) {
                    value = list[i];
                    if (iterator.call(thisArg, value, i, list)) {
                        return value;
                    }
                }
                return undefined;    
            };
        }

        var theName = myns.dataList.find(function(entry) {
            return entry.name === selfName;
        });

        expect(2 + 2).not.toEqual(4); /* doesn't get here because of TypeError */
    });
 });