Let's say I have a class like following:
class SomeClass {
constructor(a, b) {
this.a = a;
this.b = b;
}
}
How can I test through Jest that constructor was initialized the right way? Say... this.a = a
and this.b = b
and not vice versa?
I know that I can execute toBeCalledWith
but that won't let me check the constructor's logic. I was also thinking about making mockImplementation
but in this case it seems pointless as I will rewrite the logic, or I may not be aware of all the nuances of creating mocks
In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). Since calls to jest. mock() are hoisted to the top of the file, Jest prevents access to out-of-scope variables.
To test classes with Jest we write assertions for static and instance methods and check if they match expectations. The same process we use when testing functions applies to classes. The key difference is that classes with constructors need to be instantiated into objects before testing.
Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!
Just create an instance of the object and check it directly. Since it sets them on this
, they are essentially public values:
it('works', () => {
const obj = new SomeClass(1, 2);
expect(obj.a).toBe(1);
expect(obj.b).toBe(2);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With