[英]Spy on functions without objects
我正在測試pub子類的發布方法。 我在beforeEach函數中創建一個回調函數並訂閱該類。 在it方法中,我發布事件並嘗試測試回調被調用,這基本上是類的工作方式。 我已經讓測試工作並且它通過但問題是我必須使用setTimeout才能使其工作。 我相信這可能不是正確的方法。
describe('publish', () => {
let testpublish;
let callback;
beforeEach(() => {
callback = function(data) { return data + 10; }
testpublish = {
'id': 'testpublish1',
'event': 'testpublish',
'callback': callback
};
subject.subscribe(testpublish);
});
it('should call the subscription function', () => {
subject.publish('testpublish', 9);
setTimeout(() => {
expect(callback).toEqual(19);
});
});
});
我最初想監視回調只是為了看它是否被調用但是Jasmine的文檔說我必須將我的方法放在一個對象中:
spyOn(obj,methodName)→{間諜}
任何有關更好的方法的建議將不勝感激。 謝謝。
PubSub類是否有用?
@Injectable()
export class Pubsub {
private events: any = {};
public subscribe(config: any) {
let event = config['event'];
this.events[event] = this.events[event] || [];
if (this.events[event].length < 1) {
this.events[event].push(config);
} else {
for (let i = 0; i < this.events[event].length; i++) {
if (this.events[event][i].id !== config.id) {
this.events[event].push(config);
}
}
}
}
public unsubscribe(obj: Object) {
let event = obj['event'];
let id = obj['id'];
if (this.events[event]) {
this.events[event] = this.events[event].filter((eventObj) => {
return eventObj.id !== id;
});
}
if (this.events[event].length === 0) {
delete this.events[event];
}
}
public publish(event: string, data: any) {
if (this.events[event]) {
this.events[event].forEach(function(obj) {
obj.callback(data);
});
}
}
public getEvents() {
return this.events;
}
}
現有函數不能被窺探,因為間諜是一個新函數,並且對原始函數的引用已經在它被調用的地方使用。
考慮到callback
函數是在測試本身中定義的,而不是在應用程序內部,它應該首先被定義為間諜:
callback = jasmine.createSpy();
它甚至不需要做某事,因為它的返回值不會增加測試的價值。
它經過了測試
const arg = {};
subject.publish('testpublish', arg);
expect(callback.calls.count()).toBe(1);
expect(callback.calls.first().args[0]).toBe(arg);
publish
是同步的,以及類的其余部分。 不需要setTimeout
,這在這里是有害的。 如果未為測試指定done
參數,則將其視為同步,並且setTimeout
會在此測試中忽略斷言。
這個
it('should pass', () => {
setTimeout(() => {
expect(1).toBe(2);
});
});
永遠都會過去。 並且只有當套件沒有其他測試時,這將觸發SPEC HAS NO EXPECTATIONS
警告。
jasmine.createSpy('間諜')會做的。
describe('publish', () => {
let testpublish;
let callback;
let subject = new Pubsub();
beforeEach(() => {
callback = function (data) {
return data + 10;
}
testpublish = {
'id': 'testpublish1',
'event': 'testpublish',
'callback': jasmine.createSpy('spy')
};
subject.subscribe(testpublish);
});
it('should call the subscription function', () => {
subject.publish('testpublish', 9);
expect(testpublish.callback).toHaveBeenCalledWith(9);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.