模拟方法返回未定义

mocked method returning undefined

我正在为 angular 进行 jasmine 单元测试,模拟不起作用。 junit代码是:

  beforeEach(() => {
    menuSpy = spyOn(menuService, 'getMenus');
    fixture = TestBed.createComponent(MenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should test menu', () => {
    spyOn(menuSpy, 'shouldHighlight').and.returnValue(true);
    menuSpy.and.returnValue(MENUS);
    // component assertions code
  });

组成部分如下:

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: [ './menu.component.scss' ]
})
export class MenuComponent {
    menus = []
    constructor(private menuService: MenuService) {
       menus = menuService.getMenus(); // menus is always undefined
    }

此处的菜单始终为空。我整天都被困在这里。感谢任何帮助。

这是因为您在构造函数中已经使用了您的方法之后才对其进行模拟。您应该在 TestBed.createComponent 调用之前移动模拟。您可以尝试类似的操作:

it('should test menu', () => {
    spyOn(menuSpy, 'shouldHighlight').and.returnValue(true);
    spyOn(menuService, 'getMenus').and.returnValue(MENUS);
    fixture = TestBed.createComponent(MenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
   // Component assertions 
  });