Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 245
Le garcon Avatar asked Apr 17 '18 19:04

Le garcon


People also ask

How do you mock a class constructor Jest?

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.

How do you test a class using Jest?

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.

Can you use Jest to test node?

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!


1 Answers

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);
});
like image 55
samanime Avatar answered Sep 19 '22 15:09

samanime