gpt4 book ai didi

javascript - Mocha : setting varibles on `this` is antipattern?

转载 作者:行者123 更新时间:2023-11-29 11:00:49 24 4
gpt4 key购买 nike

我被下面两段代码搞糊涂了:

代码1:

describe('suit', function(){
before(() => {
this.suitData = 'suitdata';
});

beforeEach(() => {
this.testData = 'testdata';
});


it('test', done => {
console.log(this.suitData)// => suitdata
console.log(this.testData)// => testdata
})
});

代码2:

describe('suit', function(){
const suitData = 'suitdata';
const testData = 'testdata';

before(() => {
});

beforeEach(() => {
});


it('test', done => {
console.log(suitData)// => suitdata
console.log(testData)// => testdata
})
});

code1 还是 code2 哪个更好?我认为 code1 是一种反模式。我说得对吗?

谢谢

最佳答案

我不会使用 this 来存储值。

Mocha 的值(value)观与您的值(value)观发生冲突的风险

this 上下文已经包含一些由 Mocha 设置的值作为其公共(public) API 的一部分(例如 this.timeout),并且有一些值不是正式的记录在案但对使用很有用(例如,this.test)。如果您在 this 上设置变量,您可能会与 Mocha 的变量发生冲突。例如,如果用字符串覆盖 this.timeout 函数,那么如果您想更改超时,则不能使用 call this.timeout。在您出于自己的目的使用 this.timeout 的大型套件中,稍后修复冲突可能代价高昂。还有一个问题是,现在不冲突的名称​​可能会在未来的 Mocha 版本中冲突。

如果您在第二个示例中使用闭包,则不会有任何冲突。

this 的意外行为

Boneskull,GitHub 上 Mocha 的所有者之一,在 comment 中说:

I would strongly urge users to not use this for storing values, ever.

这是在 issue report 的上下文中在使用 this 存储值时显示意外结果。这是另一个 issue关于 this 的意外行为。 this 在测试之间的管理方式没有记录在案,因此人们想象它会以某种方式工作,但事实并非如此。需要进行的更改需要新的主要版本的 Mocha。

相反,如果您像在第二个示例中那样使用作用域,那么变量的创建和更改方式总是非常清楚,从 a) 了解 JavaScript 和 b) 阅读 Mocha 的文档(因为您需要了解一些有关顺序的信息)在其中运行 Hook 和测试)。

关于javascript - Mocha : setting varibles on `this` is antipattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47420567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com