首页 > 解决方案 > 防止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以免发生这种情况?

标签: javascripttypescriptmocha.jschai

解决方案


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 功能而不是一个错误。如果您在多个测试用例中定义同一个类,它将产生重复的运行时定义,这可以用于测试装饰器对存储装饰器实现结果的状态的影响。

因此,确保您没有同一个类的多个运行时实现的最佳方法是在一个地方定义它并像处理所有其他类实现一样导入它。


推荐阅读