所以我正在使用 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', () => {
// ...
});
});
问题是由于 typescript 错误,我无法运行它:
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) => {
~~~~~~~~~~~~~~~~~~~~~~~
我还尝试使用 objects
的 array
而不是 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][]
.
关于javascript - Jest test.each 的类型不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61173326/