Joh*_*nes 5 javascript testing
来自茉莉花文档(http://jasmine.github.io/2.0/introduction.html):
这个关键字
在beforeEach,it和afterEach之间共享变量的另一种方法是通过this关键字.每个规范的beforeEach/it/afterEach都将此作为>相同的空对象,为下一个规范的beforeEach/it/afterEach设置为空.
我在Javascript中对此的理解是,这与实际函数的范围有关.所以我希望它会在beforeEach/it/afterEach中绑定到上下文不同的上下文(取决于函数的上下文).
例如
describe('Spec', function (){
var eachThis = null;
beforeEach(function(){
eachThis = this;
});
it('check this', function(){
except(this).toEqual(eachThis);
}
};
Run Code Online (Sandbox Code Playgroud)
所以这个测试应该通过.
茉莉花改变了这种行为还是我弄错了?
我认为你的例子可能有一些问题,但你认为 jasminethis在使用beforeEach、beforeAll等时操纵引用是正确的。
这是一个说明性示例 - 请注意,下面列出的所有期望都将通过:
(function() {
describe("without beforeEach", function () {
(function() {
// this is not inside of a beforeEach call
this.dog = "Spot";
alert(this.dog);
})();
it("should not have access to a dog property from `this`", function () {
expect(this.dog).toBeUndefined(); // because there is no `dog` member of the object currently referenced by `this`
});
});
describe("a beforeEach test", function () {
beforeEach(function () {
this.dog = "Spot";
});
it("should work now because we used `beforeEach`", function () {
expect(this.dog).toEqual("Spot");
});
});
})();
Run Code Online (Sandbox Code Playgroud)
一般来说,您对在函数范围内定义“this”的想法是正确的,但是 jasmine 中的此实现演示了如何提供由“this”关键字引用的特定对象(如果您愿意)。在 javascript 中完成此操作的典型方法是使用Function.prototype.apply()它,它允许您传入任意对象this作为函数的第一个参数进行引用。
| 归档时间: |
|
| 查看次数: |
1614 次 |
| 最近记录: |