rya*_*zec 5 javascript unit-testing mocha.js
所以我有这个代码:
describe('main describe', function() {
afterEach(function() {
//this.prop === undefined
});
describe('sub', function() {
it('should do something', function() {
this.prop = 'test';
});
});
});
Run Code Online (Sandbox Code Playgroud)
我不知道为什么this.prop
在main
afterEach
是undefined
因为后续的代码按预期方式工作:
describe('main describe', function() {
afterEach(function() {
//this.prop === 'test'
});
it('should do something', function() {
this.prop = 'test';
});
});
Run Code Online (Sandbox Code Playgroud)
为什么第一个代码不能正常工作,尽管this.prop应该相等'test'
而不是undefined
?
this
关键字是否仅describe
与其直接包含的函数相关联?
Lou*_*uis 24
是的,每个人都describe
得到一个新的Context
对象.(我提到的所有类都可以在Mocha的源代码中找到.)你可以得到你想要做的事情:
describe('main describe', function() {
afterEach(function() {
console.log(this.prop);
});
describe('sub', function() {
it('should do something', function() {
this.test.parent.ctx.prop = 'test';
});
});
});
Run Code Online (Sandbox Code Playgroud)
这条线this.test.parent.ctx.prop
是关键.this
在Context
与相关it
的呼叫.this.test
是Test
与it
调用关联的对象.this.test.parent
是Suite
与describe
立即包含该it
调用的调用关联的对象.this.test.parent.ctx
是describe
调用出现的有效上下文,它恰好this
与afterEach
调用中的上下文相同.
我实际上建议不要遍历Mocha的内部结构,而是做以下事情:
describe('main describe', function() {
var prop;
afterEach(function() {
console.log(prop);
});
describe('sub', function() {
it('should do something', function() {
prop = 'test';
});
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6553 次 |
最近记录: |