简体   繁体   English

类型错误:expect(...).not.toBe 不是函数

[英]TypeError: expect(...).not.toBe is not a function

Doing an exercise where I re-implement some functionality found in the Jasmine test framework.做一个练习,我重新实现在 Jasmine 测试框架中找到的一些功能。 Specifically, I am running this line:具体来说,我正在运行这条线:

expect(false).not.toBe(true)

and I get a TypeError saying that toBe does not exist as a function.我收到一个 TypeError 说 toBe 不作为函数存在。 However, this line:但是,这一行:

expect(true).toBe(true)

Passes.通过。 I suspect that it's an issue with my not() function returning this.我怀疑这是我的 not() 函数返回的问题。

function ExpectedValue (val) {
    this.value = val;
    this.notted = false;

    this.not = function() {
        this.notted = !this.notted;
        return this;
    }

    this.toBe = function(b) {
        if (this.notted) {
            return this.value !== b;
        }
        else {
            return this.value === b;
        }
    }
}

function expect(a) {
    return new ExpectedValue(a);
}

console.log(expect(false).not.toBe(true));

Jasmine's not isn't a function. Jasmine's not不是一个函数。 Yours is.你的是。 But you're using it as though it were Jasmine's (without () ):但是你使用它就好像它是 Jasmine 的一样(没有() ):

console.log(expect(false).not.toBe(true));
// Note no () ---------------^

Your not needs to be an object with all of the methods of the object you return from expect , but with their meaning inverted, eg:not是具有从expect返回的对象的所有方法的对象,但它们的含义颠倒了,例如:

 function ExpectedValue (val) { var self = this; self.value = val; this.not = { toBe: function(arg) { return !self.toBe(arg); } }; this.toBe = function(b) { return self.value === b; }; } function expect(a) { return new ExpectedValue(a); } console.log(expect(false).not.toBe(true));

There, it's manual, but that's not scaleable.在那里,它是手动的,但不可扩展。 Instead, you'd have an object with all of the methods on it, and create not by running through creating functions that invert the return.相反,您将拥有一个包含所有方法的对象,而not通过运行反转返回的创建函数来创建。

arrayOfMethodNames.forEach(function(name) {
    target.not[name] = function() {
        return !target[name].apply(target, arguments);
    };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM