Le garcon
Le garcon

Reputation: 8377

How to test class constructor in Jest

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

Answers (3)

iggy12345
iggy12345

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

samanime
samanime

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

Liviath
Liviath

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

Related Questions