在Karma和Angular2中遇到令人沮丧的问题,我试图将其简化为最简单的演示:考虑这个TypeScript类,同时使用实例成员方法和静态成员方法来执行相同的操作:
export class Echo {
static classLog = console.log;
instanceLog = console.log;
static classEcho(msg: string) {
this.classLog(msg);
}
instanceEcho (msg: string) {
this.instanceLog(msg);
}
}
...然后是一个简单的纯TypeScript测试:
import {Echo} from './echo';
var e = new Echo();
e.instanceEcho('instanceEcho!');
Echo.classEcho('classEcho!');
..结果:
instanceEcho!
classEcho!
好。
然而,尝试从Jasmine验证相同的事情:
import {it} from '@angular/core/testing';
import {Echo} from './echo';
describe('Logging', ()=> {
it('instanceEcho will invoke \'console.log()\'', () => {
spyOn(console, 'log');
expect(console.log).not.toHaveBeenCalled();
var e = new Echo();
e.instanceEcho('test instanceEcho');
expect(console.log).toHaveBeenCalledWith('test instanceEcho');
});
it('classEcho will invoke \'console.log()\'', () => {
spyOn(console, 'log');
expect(console.log).not.toHaveBeenCalled();
Echo.classEcho('test classEcho');
expect(console.log).toHaveBeenCalledWith('test classEcho');
});
});
..结果:
START:
✔ instanceEcho will invoke 'console.log()'
LOG: 'test classEcho'
✖ classEcho will invoke 'console.log()'
SUMMARY:
✔ 1 tests completed
✖ 1 test failed
FAILED TESTS:
✖ classEcho will invoke 'console.log()'
Chrome 50.0.2661 (Mac OS X 10.11.5)
Expected spy log to have been called with [ 'test classEcho' ]
but it was never called.
由于静态方法确实可以正常工作,为什么Jasmine没有捕获它呢?
答案 0 :(得分:0)
我现在意识到这不是Jasmine监视TypeScript静态成员的问题,而只是一个普通的JavaScript问题,即失去了对this
的引用。如果切换到,Jasmine SpyOn将正确捕获console.log()的调用,例如:
export class Echo2 {
static classLogger = console;
instanceLogger = console;
static classEcho(msg: string) {
this.classLogger.log(msg);
}
instanceEcho (msg: string) {
this.instanceLogger.log(msg);
}
}