Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toThrowError doesn't consider inheritance #819

Closed
chge opened this issue Apr 8, 2015 · 2 comments
Closed

toThrowError doesn't consider inheritance #819

chge opened this issue Apr 8, 2015 · 2 comments

Comments

@chge
Copy link

chge commented Apr 8, 2015

toThrowError is very useful, but I think it works incorrectly with custom error classes.

function PirateError(message) {
    this.message = 'Arrggghhhh! ' + message;
}
PirateError.prototype = new Error();

describe('custom try/catch', function() {
    it('works fine in tests', function() {
        try {
            throw new PirateError();
        } catch (error) {
            expect(error).toEqual(jasmine.any(Error));
            expect(error).toEqual(jasmine.any(PirateError));
            expect(error instanceof Error).toBeTruthy();
            expect(error instanceof PirateError).toBeTruthy();
        }
    });
});

describe('toThrowError', function() {
    it('considers error inheritance', function() {
        expect(function() {
            throw new PirateError('Blow me down!');
        }).toThrowError(PirateError);
    });
});

Result:

Expected function to throw PirateError, but it threw Error.
@slackersoft
Copy link
Member

Jasmine uses the constructor attribute to determine whether the thrown error is of the desired type. When you assign the prototype of your PirateError to be a new Error() it changes the constructor to the Error function instead. If you add:

PirateError.prototype.constructor = PirateError;

after you assign the prototype your example should work.

We'd be open to a way to do this checking that didn't require re-assigning the constructor after setting the prototype, but none has come up yet.

@chge
Copy link
Author

chge commented Apr 9, 2015

But, for example, jasmine.any uses instanceof for matching. Why shouldn't toThrowError use instanceof instead of direct constructor comparison?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants