Support checking the prototype of objects
See original GitHub issueUsing ES6 classes a lot, I often construct more complex inheritance chains. At some point, I want to make sure children classes actually extend some parent class. As far as I’ve seen, there is no way to determine whether an object is the prototype of another.
It would be great to have core methods available for that:
class Foo {}
class Bar extends Foo {}
class Quz extends Bar {}
expect(Bar).to.extend(Foo);
expect(Quz).to.inheritFrom(Foo);
expect(Foo).to.be.prototypeOf(Bar);
expect(Foo).to.not.be.prototypeOf(Quz);
The inheritFrom
assertion would be most useful as Quz
does not directly extend Foo
but still inherits from it, that is a little awkward to test otherwise.
I know you could just check for an inherited method, but chances are that the child class does define (or overwrite) that method by itself.
I feel like especially the last one should be part of Chai itself. For now I’m using expect(Foo.isPrototypeOf(Bar)).to.be.true
but I wanted to leave this as a feature request.
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (4 by maintainers)
Top GitHub Comments
We’re going to put a bunch of work into Chai 5 which will include writing a bunch of new assertions that closely mimick the native API features. So we’ll continue to have an
instanceof
assertion, but we’ll likely add an.extend
assertion which can check classes that extend a super class. This has been added to our project board over here: https://github.com/chaijs/chai/projects/2. So I’ll close this issue as we’re tracking this for the chai 5 refactor.I’d prefer to have a separate assertion for this rather than overloading
instanceof
.Regarding direct/indirect inheritance, the options seem to be:
.extend
(which allows direct inheritance only) and.inherit
(which allows direct and indirect inheritance).extend
and.inherit
both allow direct and indirect inheritance unless thedirectly
flag is set (e.g.,.directly.extend
anddirectly.inherit
), in which case only direct inheritance is allowed.I’m leaning toward the second option, but haven’t formed a strong opinion yet.