要测试的嵌套函数(更改)
this.options.edit = (e: any) => {
let type: any = this.getTrasactionTypeText(e.container);
if (type !== undefined) {
let transaction: any = this.getTrasactionType(e.container);
transaction.change(() => {
console.log('testing callback');
});
}
};
茉莉花测试
it('should call back the nested function', async(() => {
class callback {
change = function() { };
}
let call = new callback();
spyOn(component, 'getTrasactionTypeText').and.returnValue('CLOSEREASON');
spyOn(component, 'getTrasactionType').and.returnValue(call);
let object: any = jasmine.createSpyObj('object', ['container', 'model']);
object.model = { isMurex: true, isBloomberg: true, isFidessa: true, isMartini: true };
component.options.edit(object);
call.change();//This is not calling the nested function
}));
答案 0 :(得分:1)
call.change();//This is not calling the nested function
没有理由应该这样做。你只是在那里调用一个函数。我认为你认为你正在触发一个事件,这个事件正由你的测试代码处理。这不是考虑它的正确方法。
您正在测试的代码只是执行一个函数,并传入一个箭头函数作为参数。一种测试方法就是检查你的函数是否被调用。例如,像这样(未经测试):
it('should call back the nested function', async(() => {
var callback = jasmine.createSpyObj('callback', ['change']);
spyOn(component, 'getTrasactionTypeText').and.returnValue('CLOSEREASON');
spyOn(component, 'getTrasactionType').and.returnValue(callback);
let object: any = jasmine.createSpyObj('object', ['container', 'model']);
object.model = { isMurex: true, isBloomberg: true, isFidessa: true, isMartini: true };
component.options.edit(object);
expect(callback.change.calls.count()).toBe(1);
}));
进一步扩展,您可以检查传入调用的参数是否为函数,然后您可以在测试中自行执行,并断言。例如:
it('should pass a function into transaction.change()', async(() => {
var callback = jasmine.createSpyObj('callback', ['change']);
spyOn(component, 'getTrasactionTypeText').and.returnValue('CLOSEREASON');
spyOn(component, 'getTrasactionType').and.returnValue(callback);
let object: any = jasmine.createSpyObj('object', ['container', 'model']);
object.model = { isMurex: true, isBloomberg: true, isFidessa: true, isMartini: true };
component.options.edit(object);
// Validate that the transaction.change() function was called once.
expect(callback.change.calls.count()).toBe(1);
// Validate that the function was given a single argument.
var args = callback.change.calls.first().args;
expect(args.length).toBe(1);
// Validate that the single argument is itself another function.
var actualFunc = args[0];
expect(typeof actualFunc).toBe('function');
// Execute the other function, and validate that it does xyz.
actualFunc();
// expect(...).toBe(...);
}));