javascript - Jasmine 单元测试当前上下文或此变量

标签 javascript unit-testing jasmine

我一直在研究这篇关于 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");
  });
});

此示例在 beforeEachit 中使用 this.episode。据我所知JS不是这样工作的。 this.episode 在描述 block 中根本不起作用?

最佳答案

Jasmine 引入了一种通过 this 关键字在 beforeEachitafterEach 之间共享变量的新方法。

您还应该知道每个规范的 beforeEachitafterEach 都将 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/

相关文章:

node.js - 使用 Node js Mocha 运行单个测试文件

javascript - 如何用 jasmine 监视 localStorage 方法

AngularJS Jasmine 2.0 异步测试超时

javascript - 一起使用 CasperJS 和 sitespeed.io

php - 谷歌地图不显示

javascript - 子元素点击也触发父元素 - Reactjs

java - 使用 junit @Rule、expectCause() 和 hamcrest 匹配器

java - 自动(半)创建单元测试?

angularjs - 使用带有 angularjs 的 selenium 服务器在 Protractor 中描述后做一些事情

javascript - 向 Google map 添加自定义控件(添加流量层切换)