如何使用describe.each添加玩笑测试的类型?

2024-01-29

const has = (object: Record<string, unknown>, key: string) => {
    return object != null && hasOwnProperty.call(object, key)
};

有.test.ts

describe('has', () => {
    const obj = {
        name: 'name',
        1: 1,
        false: false,
        undefined: undefined
    };
    describe.each([
        ['name', true],
        [1, true],
        [false, true],
        [undefined, true],
        ['no-such-key', false]
    ])('when key = %s', (key, expected) => {
        it(`should return ${expected}`, () => {
            expect(has(obj, key)).toBe(expected);
        });
    });
});

有人有为玩笑测试添加类型的经验吗?我在用describe.each循环数据集。尽管我能够成功运行测试,但我想解决该打字问题。有人能帮我吗?


您似乎没有最新版本的 jest 类型,请尝试更新软件包@types/jest到最新版本(它包含类型定义Each https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jest/index.d.ts#L294界面)。

如果由于某些原因这是不可能的,您可以随时使用称为“扩展”的打字稿功能自行“扩展”类型声明合并 https://www.typescriptlang.org/docs/handbook/declaration-merging.html:

// jest.d.ts file

declare namespace jest {

  interface Each {
    // Exclusively arrays.
    <T extends any[]>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T) => any, timeout?: number) => void;
    // Not arrays.
    <T>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T[]) => any, timeout?: number) => void;
    (cases: ReadonlyArray<ReadonlyArray<any>>): (
        name: string,
        fn: (...args: any[]) => any,
        timeout?: number
    ) => void;
    (strings: TemplateStringsArray, ...placeholders: any[]): (
        name: string,
        fn: (arg: any) => any,
        timeout?: number
    ) => void;
  }

  interface Describe {
    each: Each
  }
}

您可能还需要指定类型根 https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types配置选项,以便打字稿可以选择您的自定义类型

Upd:抱歉,我刚刚注意到您的问题并非没有Each界面但在类型不正确。 在您的情况下,打字稿似乎无法正确推断类型,因此您可能需要显式指定泛型类型,例如:

type TestTuple = [string | number | boolean, boolean];

describe.each<TestTuple>([
  ['name', true],
  [1, true],
  [false, true],
  [undefined, true],
  ['no-such-key', false]
])('when key = %s', (a, b) => {
    // do your stuff
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用describe.each添加玩笑测试的类型? 的相关文章

随机推荐