问题描述
比方说我有一个像下面这样的课程:
Let's say I have a class like following:
class SomeClass {
constructor(a, b) {
this.a = a;
this.b = b;
}
}
如何通过Jest测试构造函数是否已正确初始化?说... 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?
我知道我可以执行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中测试类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!