Reputation: 8377
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
Upvotes: 19
Views: 41974
Reputation: 1383
if you know where the class is coming from you can do something like this:
jest.mock('path/to/module');
...
it('should work', () => {
const a = Symbol();
const b = Symbol();
expect(SomeClass).toBeCalledWith(a, b);
});
Upvotes: 3
Reputation: 26547
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);
});
Upvotes: 26
Reputation: 41
You can simply check the instance properties after initializing the class. Basicly the same as you can test the side effects of any function.
const a = Symbol();
const b = Symbol();
const classInstance = new SomeClass(a, b);
expect(classInstance.a).toBe(a);
expect(classInstance.b).toBe(b);
Upvotes: 4