如何使用describe.each添加用于笑话测试的类型? [英] How to add types for jest test with describe.each?

查看:33
本文介绍了如何使用describe.each添加用于笑话测试的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

has.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 遍历数据集.尽管我能够成功运行测试,但我想修复该打字问题.有人可以帮我吗?

Does anyone have experience adding types for jest tests? I am using describe.each to loop over datasets. Though I am able to run the tests successfully, I want to fix that typing issue. Can someone help me?

推荐答案

您似乎没有最新版本的玩笑类型,请尝试将软件包 @ types/jest 更新到最新版本(其中包含每个的类型定义界面).

It seems that you don't have latest version of types for jest, try to update package @types/jest to latest version (it contains type definition for Each interface).

如果由于某些原因无法实现,您可以随时使用称为声明合并:

If that's not possible for some reasons you can always "extend" the types yourself using typescript feature called declaration-merging:

// 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
  }
}

您可能还需要指定 typeRoots 配置选项,以便打字稿可以选择您的自定义类型

You might need also to specify typeRoots configuration option so that typescript can pick up your custom types

更新:抱歉,我只是注意到您的问题并非不是 Each 界面,而是不正确的类型.在您的情况下,打字稿似乎无法正确推断类型,因此您可能需要明确指定通用类型,例如:

Upd: Sorry, I just noticed that your issue is not in absence of Each interface but in incorrect type. It seems that in your case typescript cannot infer the type correctly so you might want to specify generic type explicitly, e.g.:

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
});

这篇关于如何使用describe.each添加用于笑话测试的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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