简体   繁体   中英

Wrong type of error when testing javascript function

I am trying to test the following code:

  /** ABSTRACT METHOD PLACEHOLDER */
MyResult.prototype.get = throwNotImplementedError;

function throwNotImplementedError(resultId) {
    throw new NotImplementedError('Please implement in Item Groups and Items. This call is abstract');
}

with the following test.

it('should have a placeholder for get', function(){
    expect(function(){return MyResult.get(123);}).toThrowError(NotImplementedError);
});

What ends up happenining is that a TypeError is thrown instead of my custom NotImplementedError. The type error's message is: "MyResult.get is not a function".

I'm wondering if it might have something to do with calling the variable in the prototype 'get' but I think I've seen examples like this where they name javascript classes and use a custom method that they call get. It seems to work for other calls.

Do you have any advice on why it doesn't work for this call?

The error is completely correct.

You defined MyResult.prototype.get , which has nothing to do with MyResult.get .

You probably want to create an instance.

It's a prototype function

So you have to test get function with an instance of an object like this:

it('should have a placeholder for get', function(){
    var resultObj = new MyResult(); // Create an instance of your object
    expect(function(){return resultObj.get(123);}).toThrowError(NotImplementedError);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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