在茉莉花中测试嵌套函数

时间:2018-11-16 04:13:02

标签: angular jasmine

我要在项目中进行测试,而我要测试的函数是一个嵌套函数,函数中有该函数

像这样的功能

  ngOnInit() {
    this.getMenu()
  }

这是我的测试规格:

    describe('NavigationComponent', () => {
        let component: NavigationComponent;
        let fixture: ComponentFixture<NavigationComponent>;

        beforeEach(async(() => {
          TestBed.configureTestingModule({
            imports: [

            ],
            providers: [
              { provide: AuthenticationService, useClass: MockAuthenticationService }
            ]
          })
          .compileComponents();
        }));

        beforeEach(() => {
          fixture = TestBed.createComponent(NavigationComponent);
          //navComponent = TestBed.createComponent(NavigationComponent);
          component = fixture.componentInstance;
          fixture.detectChanges();
        });

  it('getMenu should called', ()=>{
        spyOn(component, 'getMenu');                  
        fixture.detectChanges();                      
        expect(component.getMenu).toHaveBeenCalled();
    })

当我测试ngOnInit时可以使用,但是我不知道如何测试“ getMenu”

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您可以检查运行getMenu()时是否调用了方法ngOnInit()

您要做的是监视该方法,然后进行验证。

spyOn(compInstance, 'getMenu');                  //spy on getMenu
fixture.detectChanges();                         //calls ngOnInit() and updates dom
expect(compInstance.getMenu).toHaveBeenCalled(); //verify getMenu() invokation

如果要测试getMenu()的逻辑,则可以直接从测试规范中调用它,然后验证其输出。

let res = compInstance.getMenu();
expect(res).toBe('pizza');