使用 Typescript 在 Mocha 测试中检索当前测试的名称

Retrieve the current test's name within a Mocha test using Typescript

这个问题与this one非常相似,但有一个非常显着的区别:使用了打字稿。

我正在尝试从 mocha 测试中获取当前测试标题,但由于使用了打字稿,因此此代码不起作用:

import 'mocha';

describe("top", () => {
    console.log(this.title);
    console.log(this.fullTitle());

    it("test", () => {
        console.log(this.test.title);
        console.log(this.test.fullTitle());
    });
});

打字稿模糊了 this 并且无法再访问原生 JavaScript 的 this

有没有人遇到过这种情况?有什么解决方法吗?

你的问题不是你使用 TypeScript,而是你使用箭头函数。

箭头函数自动将 this 绑定到定义函数的 this

因为它们都使用箭头函数,所以你的 this 是在全局级别找到的 this,它要么是 global 在严格模式之外,要么是 undefined在严格模式下。 (因为你使用的是 ES 模块,所以根据规范你会自动处于严格模式)

进口'mocha';

describe("top", function() {
    console.log(this.title);
    console.log(this.fullTitle());

    it("test", function() {
        console.log(this.test.title);
        console.log(this.test.fullTitle());
    });
});