单元测试类型脚本类型



我的一个模块中有以下导出:

export class Action1 implements Action {}
export class Action2 implements Action {}
export type ActionsUnion =
| Action1
| Action2;

我正在努力找出测试ActionsUnion的最佳方法,以确保它是我定义的类型。例如:

it('should have the correct types', () => {
expect(typeof Action1).toEqual(ActionsUnion);
expect(typeof Action2).toEqual(ActionsUnion);
});

当然,由于我使用ActionsUnion作为变量,上述方法不起作用。关于如何实现上述目标,有什么想法吗?

对于上下文,我使用angular、ngrx和jasmine。

tsafe启用单元测试类型,例如:

// This test file is not meant to be executed, if there is not TS errors, it passes.

import { assert, Equals } from "tsafe";
declare function myFunction<T extends string>(arr: T[]): T;
{
const got = myFunction([ "a", "b", "c" ]);
type Got = typeof got;
type Expect = "a" | "b";
// Here we have a TS error, as we should, because:
// Got is        "a" | "b" | "c"
// and Expect is "a" | "b"
assert<Equals<Got, Expect>>();
}
{
const got = myFunction([ "a", "b", "c" ]);
type Got = typeof got;
type Expect = "a" | "b" | "c";
// ✅ Got and Expect are the same type
assert<Equals<Got, Expect>>();
}
{
//@ts-expect-error: We shouldn't be allowed to pass numbers
myFunction([ "a", 42, "c" ]);
}
{
// Here we got some red because we say we expect an 
// error but the expression is valid
//@ts-expect-error
myFunction([ "a", "b", "c" ]);
}
{
const got = myFunction([ "a", "b", "c" ]);
type Got = typeof got;

// We can also validate that 
assert<Got extends string ? true : false>();

}
{
type T = "a" | "b";
type U = string;
// We expect that T extends U
assert<T extends U ? true : false>();
}

在问题的例子中:

import { assert } from "tsafe/assert";
import type { Extends } from "tsafe";
type Action= { _signature: undefined; }
class Action1 implements Action {
_signature: undefined;
}
class Action2 implements Action {
_signature: undefined;
}
export type ActionsUnion =
| Action1
| Action2;
assert<Extends<Action1, ActionsUnion>>();

披露:我是作者。

我还没有尝试过联合,但你可能想尝试jasmine.any(Type(。在这种情况下,你上面的代码是:

it('should have the correct types', () => {
expect(Action1).toEqual(jasmine.any(ActionsUnion));
expect(Action2).toEqual(jasmine.any(ActionsUnion));
});

此处提供详细信息:https://jasmine.github.io/2.0/introduction.html#section-Matching_Anything_with_%3Code%3Jasmine.any%3C/code%3E

最新更新