我的组件代码有:
function aa() {
this.component.grid = createItem();
this.component.grid.instance.options.addEventListener('eventAbc',() => {
this.bbb ();
})
}
function bbb() {
console.log("dummy func");
}
在 component.spec.ts 文件中:
let content;
setup() {
content = jasmine.createSpyObj('content', ['createItem']);
content.createItem.and.callFake(() => {
return {
grid: {
instance: {
options: {
addEventListener: (event, action) => {}
}}}}}
it('testing method aa', () => {
spyOn(component.grid.instance.gridOptions, 'addEventListener').andCallThrough();
spyOn(component, 'bbb').and.callThrough();
component.aa();
expect(component.grid.instance.gridOptions.addEventListener).toHaveBeenCalled();
expect(component.bbb).toHaveBeenCalled();
}
我想了解如何模拟触发“abcEvent”,以便测试进入事件监听器的真实回调并调用 bbb 方法。
最佳答案
我会在回调中调用 action
,以便调用 bbb
方法。
类似这样的事情:
content.createItem.and.callFake(() => {
return {
grid: {
instance: {
options: {
addEventListener: (event, action) => {
// !! add the following line, call action method so when you pass
// bbb there it will be called
action();
}
}}}}}
关于angular - 如何在 jasmine 测试中模拟事件回调触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74174490/