Ionic3-测试。测试是否将页面推送到NavigationStack上

时间:2018-12-11 16:24:51

标签: testing ionic3

我真的是测试新手。我设置了TedBed。现在,我尝试测试如下所示的第一个组件“ MyApp”:

@Component({
  templateUrl: 'app.html'
})
export class MyApp implements OnInit {
  rootPage:any = HomePage;

  constructor(
    private app:App, 
   ) {

  }

  pageTwo() {
    let navs = this.app.getActiveNavs();
    let nav = navs[0]
    nav.push(AnotherPage);
  }


  ngOnInit() {

  }
}

模板:

<ion-menu [content]="content" persistent="true">
    <ion-header>
        <ion-navbar>
            <ion-title>
                MyApp
            </ion-title>
        </ion-navbar>
    </ion-header>
    <ion-content>
        <ion-list>
            <button menuClose (click)="pageTwo()" ion-item>
                <ion-label>
                    AnotherPage
                </ion-label>
            </button>
        </ion-list>
    </ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

如您所见,如果单击菜单按钮,我将导航到“ AnotherPage”。这正在起作用-现在我尝试测试此行为:

describe('MyApp Component', () => {
  let fixture;
  let component;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyApp],
      imports: [
        IonicModule.forRoot(MyApp),
      ],
      providers: [
        {provide: NavController, useFactory: () => NavControllerMock.instance()},
        {provide: App, useFactory: () => AppMock.instance()},
      ]
    })
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyApp);
    fixture.detectChanges();
    component = fixture.componentInstance;
  });

  it('should be created', () => {
    expect(component instanceof MyApp).toBe(true);
  });

  it('should navigate to Antoherpage if pageTwo() is called', () => {
    component.pageTwo()
    // ...
  });


});

我不知道该怎么做,以测试在调用方法“ pageTwo”后是否将“ AnotherPage”推送到Navstack中。

预先感谢

1 个答案:

答案 0 :(得分:0)

因此,经过一些研究,我开始尝试了。比我想象的要容易:

  it('should navigate to Antoherpage if pageTwo() is called', () => {
    component.pageTwo()
    expect(nav.push).toHaveBeenCalledWith(AnotherPage);
  });

因为我使用了ion-mocks软件包(https://github.com/stonelasley/ionic-mocks)。我不必手动监视nav.push。