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
遍历数据集。尽管我能够成功运行测试,但我想修复该打字问题。有人可以帮我吗?
答案 0 :(得分:0)
看来您没有最新类型的玩笑,请尝试将软件包@types/jest
更新到最新版本(它包含Each界面的类型定义)。
如果由于某些原因无法实现,您可以随时使用称为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配置选项,以便打字稿可以选择您的自定义类型
更新:
抱歉,我只是注意到您的问题并非没有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
});