我正在为 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
}
此处的菜单始终为空。我整天被困在这里。任何帮助表示赞赏。
答案 0 :(得分:1)
这是因为在构造函数中已经使用了方法之后,您正在模拟它们。您应该在 @RestController
@RequestMapping("/fruit")
public class FruitInsertController {
@Autowired
FruitInsertService fruitInsertService;
@PostMapping("/insert.do")
public ResponseEntity<Object> insertFruit(FruitEntity fruitEntity){
return ResponseEntity.ok(fruitInsertService.doInsert(fruitEntity));
}
}
调用之前移动您的模拟。您可以尝试以下操作:
TestBed.createComponent