防止 Typescript class 脚手架/设置在一个 mocha 中它的功能不会干扰另一个?

Preventing Typescript class scaffolding / setup in one mocha it function from interfering with another?

我正在用 Mocha 编写打字稿测试,并定义了这样的测试:

    describe("IsDefined", () => {
    it("should work right ...", () => {
        class Test {
        @IsDefined() p1: String = "";
        @IsDefined() p2: Date = new Date();
        @IsDefined() p3: Number = 0;
        }

然后在同一 describe 块中的另一个测试中,我重新定义了 Test class,如下所示:

    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();

那没有用。不知何故,来自早期 it 方法的 Test class 仍被用于创建我正在创建的 instance,因此看不到传递给装饰器的选项。

如果我将 class 重命名为 Test2,那么我会得到正确的结果,但我不想依赖设置中使用的 classes 的正确命名。

在每个 it 方法之前设置的正确方法是什么,这样就不会发生这种情况?

Mocha 没有尝试将 typescript class 定义隔离到特定的测试范围,这实际上是一件好事。例如,如果在 运行 时间内加载相同 class 的多个定义,class 实例上 运行 的装饰器可能会产生无效状态。这是在我处理上述内容时发生的,结果我得到了一个更好的缓存设计。这是:

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

因此,确保您没有多次 运行 同一 class 实现的最佳方法是在一个地方定义它,然后像导入所有其他地方一样导入它class 实施。