javascript - 防止Typescript类脚手架/设置在一个摩卡咖啡中它的功能干扰另一个?
问题描述
我在 Mocha 中编写打字稿测试,并定义了这样的测试:
describe("IsDefined", () => {
it("should work right ...", () => {
class Test {
@IsDefined() p1: String = "";
@IsDefined() p2: Date = new Date();
@IsDefined() p3: Number = 0;
}
然后在同一块内的另一个测试中,describe
我重新定义了这样的Test
类:
it("should have accurately mapped ValidationContext values.", () => {
const options: ValidationOptions = {
each: true,
message: "Wazzzzaaaaaaapppppp????!!!!"
};
class Test {
@IsDefined(options) p1: String = "";
@IsDefined(options) p2: Date = new Date();
@IsDefined(options) p3: Number = 0;
}
const instance = new Test();
那没有用。不知何故,Test
早期it
方法中的类仍然被用来创建instance
我正在创建的,所以没有看到传递给装饰器的选项。
如果我将类重命名为,Test2
那么我会得到正确的结果,但我不想依赖于设置中使用的类的正确命名。
在每种方法之前设置的正确方法是什么,it
以免发生这种情况?
解决方案
Mocha 没有尝试将 typescript 类定义隔离到特定的测试范围,这实际上是一件好事。例如,如果在运行时加载同一类的多个定义,则在类实例上运行的装饰器可能会产生无效状态。这发生在我使用上述内容时,因此我最终获得了更好的缓存设计。这里是:
/**
* If the ValidationContext instance is absent it is created, otherwise
* the context is placed in the cache specific to the class decorated.
* @param key
* @param vc
* @throws Error if attempting to add a ValidationContext that has already been added
*
* The exception thrown indicates that duplicate class definition exist in the runtime.
*/
private static pushIfAbsent(key: string, vc: ValidationContext):void {
if (this.cache[key] == null) {
const validationContextMap: IValidationContextIndex = {};
validationContextMap[vc.getSignature()]= vc;
this.cache[key] = validationContextMap;
} else {
if (this.cache[key][vc.getSignature()]) {
throw new Error(`The ValidationContainer already contains context with signature ${vc.getSignature()}.`);
}
this.cache[key][vc.getSignature()]=vc;
}
}
所以我认为这是一个 Mocha 功能而不是一个错误。如果您在多个测试用例中定义同一个类,它将产生重复的运行时定义,这可以用于测试装饰器对存储装饰器实现结果的状态的影响。
因此,确保您没有同一个类的多个运行时实现的最佳方法是在一个地方定义它并像处理所有其他类实现一样导入它。
推荐阅读
- typescript - 打字稿运行时错误:无法读取未定义的属性“长度”
- excel - Excel SUMPRODUCT ISNUMBER 搜索范围并忽略范围内的空空白单元格
- python - 如何将输入限制为一个字母?
- java - java如何防止从外部库输出错误
- domain-driven-design - ABAP DDD 如何通过 RFC 从聚合中正确实现添加/更新/删除子项?
- java - 'java' 命令是否编译 Java 程序?
- vue.js - VueJS:为生产构建时出错
- postgresql - psycopg2 游标获取结果集的所有顺序
- maven - 如何将 Maven 日志中的测试运行次数与源代码匹配?
- hive - 如何插入非重复项,我可以将 MERGE 与自引用一起使用吗?