Unit tests and navigator



  • I am working on some unit tests and I almost figured out how to mock the ons-navigator but my spy is not working the right way. I am using the latest Onsen 1 Version.

    Here is some code written in CoffeeScript

    //Test
    pageNavigator = "<ons-navigator var='pageNavigator'></ons-navigator>";
    navigatorDOM = @$compile(pageNavigator)(@$scope);
    pageNavigator = new @NavigatorView(@$scope, navigatorDOM, null)
    spyOn(pageNavigator, 'pushPage').and.callThrough()
    @controller.showEvent(event)
    expect(pageNavigator.pushPage).toHaveBeenCalled()
    
    //Controller
    vm.showEvent = (event) ->
        pageNavigator.pushPage('event.html')
    

    There are no errors considering the pageNavigator and I think it is created correctly but I get the following message if I run this test: Expected spy pushPage to have been called.

    Thanks for your help and I think this should be documented somewhere if we get this to work

    Cheers



  • I finally figured it out!

    To mock a ons-navigator do the following:

    //your code here (coffeScript)
    dom = "<ons-navigator var='pageNavigator'></ons-navigator>";
    navigatorDOM = @$compile(dom)(@$scope);
    new @NavigatorView(@$scope, navigatorDOM, @controller)
    spyOn(pageNavigator, 'pushPage').and.callThrough()
    
    @controller.showEvent(event)
    
    expect(pageNavigator.pushPage).toHaveBeenCalled()
    

    Now I can finally write more unit tests!
    I hope this helps somebody else, because e2e is nice and fun but unit tests are important as well.

    Cheers


Log in to reply