在jest中编写单元测试时预期会出现特定错误

w41d8nur  于 2022-12-25  发布在  Jest
关注(0)|答案(2)|浏览(163)

我使用了nestjs(6.5.0)和jest(24.8),并且有一个抛出错误的方法:

public async doSomething(): Promise<{ data: string, error?: string }> {
    throw new BadRequestException({ data: '', error: 'foo' });
  }

如何编写一个单元测试来检查我们是否得到了预期的异常和预期的数据呢?显而易见的解决方案是:

it('test', async () => {
  expect(await userController.doSomething())
    .rejects.toThrowError(new BadRequestException({ data: '', error: 'foo'});
});

但这不起作用,因为new BadRequestException()创建了一个具有不同调用堆栈的对象。

6yoyoihd

6yoyoihd1#

jest documentation中的示例相比,这里可能有两个问题。

  • await应在expect参数之外
  • rejects意味着抛出了一个错误,因此您要测试是否相等

例如:

it('test', async () => {
  await expect(userController.doSomething())
    .rejects.toEqual(new BadRequestException({ data: '', error: 'foo'});
});
30byixjq

30byixjq2#

回答我自己的问题:
使用自定义匹配器(见下文),测试可以编写为:

it('test', async () => {
  await expect(userController.doSomething()).rejects.toContainException(
    new BadRequestException({ data: '', error: 'foo' }),
  );
});

自定义匹配器:

import { HttpException } from '@nestjs/common';

// ensure this is parsed as a module.
export {};

// https://stackoverflow.com/questions/43667085/extending-third-party-module-that-is-globally-exposed

declare global {
  namespace jest {
    interface Matchers<R> {
      toContainException: (expected: R | any) => {};
    }
  }
}

// this will extend the expect with a custom matcher
expect.extend({
  toContainException<T extends HttpException>(received: T, expected: T) {
    const success =
      this.equals(received.message, expected.message) &&
      this.equals(received.getStatus(), expected.getStatus());

    const not = success ? ' not' : '';
    return {
      message: () =>
        `expected Exception ${received.name}${not} to be ${expected.name}` +
        '\n\n' +
        `Expected: ${this.utils.printExpected(expected.message)}, ` +
        `status: ${this.utils.printExpected(expected.getStatus())} \n` +
        `Received: ${this.utils.printReceived(received.message)}, ` +
        `status: ${this.utils.printReceived(received.getStatus())}`,
      pass: success,
    };
  },
});

相关问题