如何在Jest中测试类构造函数 [英] How to test class constructor in Jest

查看:407
本文介绍了如何在Jest中测试类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有一个像下面这样的课程:

Let's say I have a class like following:

class SomeClass {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
}

如何通过Jest测试构造函数是否已正确初始化?说... this.a = athis.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?

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

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

推荐答案

只需创建对象的实例并直接检查即可.由于它将它们设置在上,因此它们实质上是公共值:

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

这篇关于如何在Jest中测试类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆