我一直在研究这篇关于 Jasmine 单元测试的文章。我找到了这个例子:
describe("Episode", function() {
beforeEach(function() {
this.episode = new Backbone.Model({
title: "Hollywood - Part 2"
});
});
it("should expose an attribute", function() {
expect(this.episode.get("title"))
.toEqual("Hollywood - Part 2");
});
});
此示例在 beforeEach
和 it
中使用 this.episode。据我所知JS不是这样工作的。 this.episode
在描述 block 中根本不起作用?
最佳答案
Jasmine 引入了一种通过 this
关键字在 beforeEach
、it
和 afterEach
之间共享变量的新方法。
您还应该知道每个规范的 beforeEach
、it
、afterEach
都将 this
作为同一个空对象对于下一个规范,该值设置回空。
<强> From Github
For every test (and their beforeEach/afterEach hooks), jasmine sets the receiver of each function to an initially empty object. This object, which is called userContext within Jasmine's source code, can have properties assigned to it, and gets blown away at the end of each test. In an attempt to address the issues we were having, we recently switched over to assigning variables to this object, rather than declaring them within describe and then assigning them.
这种新方法被认为更好,因为:
- 不再有全局泄密
- 含义明确
- 通过动态调用改进代码重用
- 通过惰性求值减少代码重复
关于javascript - Jasmine 单元测试当前上下文或此变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31370660/