玩笑单元测试是否调用了super() [英] Jest unit-testing if super() is called

查看:267
本文介绍了玩笑单元测试是否调用了super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义错误类,该类扩展了Javascript中的内置Error类.我想到的问题是,是否通过我的Jest单元测试调用了"super()"方法.

I have a custom error class that extends the built-in Error class in Javascript. The problem I came up with is that "super()" method is not checked if it is called or not through my Jest unit testing.

export class AppError extends Error {
  public name: string;
  public message: string;
  public status?: number;
  public data?: any;
  constructor(message: string, status?: number, data?: any) {
    super(); <-- this guy!!
    this.name = 'AppError';
    this.status = status || 500;
    this.message = message;
    this.data = data;
  }
}

有什么方法可以测试吗?谢谢.

Is there any way to test it? Thanks.

推荐答案

没有理由检查在本地ES6类或通过Babel转译的类中均未调用super().

There's no reason to check if super() is called neither in native ES6 classes nor in classes transpiled with Babel.

在子类构造函数中不调用super会导致类实例化时出错:

Not calling super in child class constructor will result in error on class instantiation:

ReferenceError:必须在派生类中调用超级构造函数,然后才能访问"this"或从派生构造函数返回

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

Babel

有可能通过模拟子类原型来检查是否调用了父构造函数(对于声明super()很有用),例如:

It may be possible to check that parent constructor is called (could be useful to assert super() arguments) by mocking child class prototype, something like:

let ParentOriginal;
let ParentMock;

beforeEach(() => {
  ParentOriginal = Object.getPrototypeOf(AppError);
  ParentMock = jest.fn();
  Object.setPrototypeOf(AppError, ParentMock);
});

it('..', () => {
  new AppError(...);
  expect(ParentMock.mock.calls.length).toBe(1);
})

afterEach(() => {
  Object.setPrototypeOf(AppError, ParentOriginal);
});

期望在本机类和使用Babel转译的类中都模拟super.

It's expected to mock super in both native classes and classes transpiled with Babel.

但是该测试是多余的,因为缺少super()会以任何方式导致错误.测试AppErrorError继承是需要在此处进行测试的所有内容:

But this test is redundant, because missing super() will result in error any way. Testing that AppError inherits from Error is everything that needs be tested here:

expect(new AppError(...)).toBeInstanceOf(Error)

这篇关于玩笑单元测试是否调用了super()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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