[英]Retrieve the current test's name within a Mocha test using Typescript
This question is very similar to this one , but has one very significant difference: typescript is used. 这个问题与此非常相似,但是有一个非常重要的区别:使用了打字稿。
I'm trying to get current test title from within the mocha test, but since typescript is used this code does not work: 我正在尝试从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());
});
});
Typescripts obscures this
and access to native JavaScript's this
is not possible anymore. 打字稿掩盖this
和访问本地JavaScript的this
是不可能的了。
Has anyone faced this situation before? 有人遇到过这种情况吗? Is there any workaround for it? 有什么解决方法吗?
Your problem isn't that you use TypeScript, it's that you use arrow functions. 您的问题不是使用TypeScript,而是使用箭头功能。
Arrow functions automatically bind this
to the this
where the function is defined. 箭头函数会自动this
绑定到定义函数的this
。
Since they all use arrow functions, your this
is the this
found at the global level, which is either global
outside of strict mode, or undefined
in strict mode. 因为它们都使用箭头功能,你this
是this
在全球层面,要么是发现了global
的严格模式之外,或undefined
严格模式。 (Since you're using ES modules, per-spec you are automatically in strict mode) (由于您使用的是ES模块,因此根据规格,您将自动进入严格模式)
import '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());
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.