How to test class constructor in Jest

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-22 04:29:28

问题


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


回答1:


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);
});



回答2:


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);


来源:https://stackoverflow.com/questions/49886244/how-to-test-class-constructor-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!