我在实际代码中遇到了这个问题,但我整理了一个简单的例子来证明这一点。
下面的代码工作正常。我在我的根目录中设置了一个变量describe()
在我的子系统中可以访问的块describe()
s' it()
blocks.
describe('simple object', function () {
var orchard;
beforeEach(function () {
orchard = {
trees: {
apple: 10,
orange : 20
},
bushes: {
boysenberry : 40,
blueberry: 35
}
};
});
describe('trees', function () {
it ('should have apples and oranges', function() {
var trees = orchard.trees;
expect (trees.apple).toBeDefined();
expect (trees.orange).toBeDefined();
expect (trees.apple).toEqual(10);
expect (trees.orange).toEqual(20);
});
it ('should NOT have pears or cherries', function() {
var trees = orchard.trees;
expect (trees.pear).toBeUndefined();
expect (trees.cherry).toBeUndefined();
});
});
});
http://jsfiddle.net/w5bzrkh9/ http://jsfiddle.net/w5bzrkh9/
但是,如果我尝试通过执行以下操作来稍微干燥我的代码,它就会崩溃:
describe('simple object', function () {
var orchard;
beforeEach(function () {
orchard = {
trees: {
apple: 10,
orange : 20
},
bushes: {
boysenberry : 40,
blueberry: 35
}
};
});
describe('trees', function () {
var trees = orchard.trees; // TypeError: Cannot read property 'trees' of undefined
it ('should have apples and oranges', function() {
expect (trees.apple).toBeDefined();
expect (trees.orange).toBeDefined();
expect (trees.apple).toEqual(10);
expect (trees.orange).toEqual(20);
});
it ('should NOT have pears or cherries', function() {
expect (trees.pear).toBeUndefined();
expect (trees.cherry).toBeUndefined();
});
});
});
http://jsfiddle.net/goqcev42/ http://jsfiddle.net/goqcev42/
嵌套内describe()
范围,即orchard
对象是未定义的,即使它是在it()
其中的块。
这是 Jasmine 开发人员有意为之的吗?可能是为了避免在 中重置对象时出现问题beforeEach()
并可能破坏一些参考文献?他们如何实现这一目标?我可以看到这有什么用处,我只是很好奇它是如何工作的。 (我的猜测是一些apply()
or call()
魔法,但我不知道如何......)
--
作为旁注,我仍然可以通过简单地使用另一个来干燥我的代码beforeEach()
block:
describe('simple object', function () {
var orchard;
beforeEach(function () {
orchard = {
trees: {
apple: 10,
orange : 20
},
bushes: {
boysenberry : 40,
blueberry: 35
}
};
});
describe('trees', function () {
var trees;
beforeEach(function() {
trees = orchard.trees;
});
it ('should have apples and oranges', function() {
expect (trees.apple).toBeDefined();
expect (trees.orange).toBeDefined();
expect (trees.apple).toEqual(10);
expect (trees.orange).toEqual(20);
});
it ('should NOT have pears or cherries', function() {
expect (trees.pear).toBeUndefined();
expect (trees.cherry).toBeUndefined();
});
});
});