javascript 如何在 Jest 中测试类构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49886244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:48:50  来源:igfitidea点击:

How to test class constructor in Jest

javascriptunit-testingjest

提问by Le garcon

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 = aand this.b = band not vice versa?

如何通过 Jest 测试构造函数是否以正确的方式初始化?说...this.a = athis.b = b不是反之亦然?

I know that I can execute toBeCalledWithbut that won't let me check the constructor's logic. I was also thinking about making mockImplementationbut 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

我知道我可以执行,toBeCalledWith但这不会让我检查构造函数的逻辑。我也在考虑制作,mockImplementation但在这种情况下似乎毫无意义,因为我将重写逻辑,或者我可能不知道创建模拟的所有细微差别

回答by samanime

Just create an instance of the object and check it directly. Since it sets them on this, they are essentially public values:

只需创建对象的实例并直接检查它。由于它将它们设置为this,因此它们本质上是公共值:

it('works', () => {
  const obj = new SomeClass(1, 2);
  expect(obj.a).toBe(1);
  expect(obj.b).toBe(2);
});

回答by Liviath

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