Jest 的类型不正确 test.each

Incorrect types for Jest test.each

所以我正在使用 Jest#test.each 来 运行 一些单元测试。

这是实际代码:

const invalidTestCases = [
  [null, TypeError],
  [undefined, TypeError],
  [false, TypeError],
  [true, TypeError],
];

describe('normalizeNames', () => {
  describe('invalid', () => {
    test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => {
      expect(() => normalizeNames(actual as any)).toThrowError(expected);
    });
  });

  describe('valid', () => {
    // ...
  });
});

问题是由于打字稿错误,我无法运行:

Argument of type '(actual: boolean | TypeErrorConstructor | null | undefined, expected: boolean | TypeErrorConstructor | null | undefined) => void' is not assignable to parameter of type '(...args: (TypeErrorConstructor | null)[] | (TypeErrorConstructor | undefined)[] | (boolean | TypeErrorConstructor)[]) => any'.
      Types of parameters 'actual' and 'args' are incompatible.
        Type '(TypeErrorConstructor | null)[] | (TypeErrorConstructor | undefined)[] | (boolean | TypeErrorConstructor)[]' is not assignable to type '[boolean | TypeErrorConstructor | null | undefined, boolean | TypeErrorConstructor | null | undefined]'.
          Type '(TypeErrorConstructor | null)[]' is missing the following properties from type '[boolean | TypeErrorConstructor | null | undefined, boolean | TypeErrorConstructor | null | undefined]': 0, 1
           test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => {
                                                       ~~~~~~~~~~~~~~~~~~~~~~~

我也尝试使用 objectsarray 而不是 2d array,像这样:

const invalidTestCases = [
  { actual: null, expected: TypeError },
  { actual: undefined, expected: TypeError },
  { actual: false, expected: TypeError },
  { actual: true, expected: TypeError },
];

describe('normalizeNames', () => {
  describe('invalid', () => {
    test.each(invalidTestCases)('some description for (%p, %p)', ({ actual, expected }) => {
      expect(() => normalizeNames(actual as any)).toThrowError(expected);
    });
  });

  describe('valid', () => {
    // ...
  });
});

...但是这样做,我无法获得 object 值的正确测试描述。

我目前不在可以测试它的地方,但添加类型注释通常可以修复该错误。

也许可以试试:

type testCaseErrorTypes = null|undefined|boolean
const invalidTestCases: [testCaseErrorTypes, typeof TypeError][] = [
  [null, TypeError],
  [undefined, TypeError],
  [false, TypeError],
  [true, TypeError],
];
test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => { … }

这应该将 invalidTestCases(testCaseErrorTypes|TypeError)[][] 转换为正确的类型 [testCaseErrorTypes, TypeError][]

由于所有 expected 值都相等,您可以只使用一维数组并将 TypeError 直接传递给 toThrowError。应该是这样的:

const invalidTestCases = [
  null,
  undefined,
  false,
  true,
];

describe('normalizeNames', () => {
  describe('invalid', () => {
    test.each(invalidTestCases)('some description for (%p)', actual => {
      expect(() => normalizeNames(actual as any)).toThrowError(TypeError);
    });
  });

  describe('valid', () => {
    // ...
  });
});