jasmine 2.0 test with a custom matcher fails: undefined is not a function

淺唱寂寞╮ 提交于 2019-12-20 10:25:09

问题


I have this function in my source file:

function gimmeANumber(){
    var x = 4;
    return x;
}

And a spec borrowed from this tutorial

describe('Hello world', function() {

    beforeEach(function() {
        this.addMatchers({
            toBeDivisibleByTwo: function() {
                return (this.actual % 2) === 0;
            }
        });
    });

    it('is divisible by 2', function() {
        expect(gimmeANumber()).toBeDivisibleByTwo();
    });

});

This is the error:

TypeError: undefined is not a function at Object. (file:///home/n/foo/jasmine/jasmine-2.0.0/dist/spec/HelloWorldSpec.js...) Thank you.


回答1:


The API for adding custom matchers has changed since 1.3. You can see the changes here.

Here is how it works now:

function gimmeANumber() {
    var x = 4;
    return x;
}

describe('Hello world', function () {

    beforeEach(function () {
        jasmine.addMatchers({
            toBeDivisibleByTwo: function () {
                return {
                    compare: function (actual, expected) {
                        return {
                            pass: (actual % 2) === 0
                        };
                    }
                };
            }
        });
    });

    it('is divisible by 2', function () {
        expect(gimmeANumber()).toBeDivisibleByTwo();
        expect(5).not.toBeDivisibleByTwo();
    });

});


来源:https://stackoverflow.com/questions/23986665/jasmine-2-0-test-with-a-custom-matcher-fails-undefined-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!