2017-08-02 148 views
0

因此,在測試中,我已經提供了一個嘲笑類的AuthService如何在Angular中模擬服務的響應函數?

{ provide: AuthService, useClass: AuthServiceMock } 

這種嘲笑服務有一個isAuthorized()功能,始終還真;

而且,在規範,看起來像這樣的

it('init root with LOGIN PAGE if is authenticated,() => { 

    expect(comp['rootPage']).toBe(LoginPage); // true! 

}); 

it('init root with WELCOME PAGE if is not authenticated,() => { 

    // Here I need to change the result of isAuthorized() 
    // so inside the AuthServiceMock returns false 
    expect(comp['rootPage']).toBe(WelcomePage); // false :(

}); 

編輯:添加的全部代碼描述

describe('Component: Root Component',() => { 

    beforeEach(async(() => { 

     TestBed.configureTestingModule({ 

      declarations: [MyApp], 

      providers: [ 
       { provide: AuthServiceProvider, useClass: AuthServiceProviderMock }, 
       ConfigProvider, 
       StatusBar, 
       SplashScreen 
      ], 

      imports: [ 
       IonicModule.forRoot(MyApp) 
      ] 

     }).compileComponents(); 

    })); 

    beforeEach(() => { 

     fixture = TestBed.createComponent(MyApp); 
     comp = fixture.componentInstance; 

    }); 

    it('initialises with a root page of LoginPage if not authorized',() => { 

     expect(comp['rootPage']).toBe(LoginPage); 

    }); 

}); 

回答

1

你真的錯過了很多的信息在這裏,但讓我嘗試幫助。

希望AuthServiceMock.isAuthorized其實是一個茉莉間諜。這可以定義的類時要做到:

class AuthServiceMock { 
    isAuthorized = jasmine.createSpy('auth.isAuthorized').and.returnValue(true); 
} 

如果是這種情況,並且isAuthorized是間諜,那麼你可以變化你的間諜在你的第二個測試的返回值如下:

it('init root with WELCOME PAGE if is not authenticated', 
    inject([AuthService], (mockAuthInstance) => { 
    mockAuthInstance.isAuthorized.and.returnValue(false); 
    expect(comp.rootPage).toBe(WelcomePage); 
    }) 
); 

在本例中,我們使用了預定義的注入規則,並將模擬服務直接注入到我們的測試中。

如果isAuthorized還不是間諜,那麼你可以把它在測試間諜,如下

it('init root with WELCOME PAGE if is not authenticated', 
    inject([AuthService], (mockAuthInstance) => { 
    spyOn(mockAuthInstance, 'isAuthorized').and.returnValue(false); 
    expect(comp.rootPage).toBe(WelcomePage); 
    }) 
); 
+0

嗨傑森,問題是,我沒有在這個範圍內的mockAuthInstance。我測試app.component.ts,內部注入AuthService。 在這個範圍內,我只有comp和fixture變量。我將編輯主要問題並添加完整的代碼示例。謝謝! – eneoes

+0

這就是'inject()'方法的作用。他們會將相同的事情注入到你的測試中。在上面的兩個例子中,在測試名稱後面有[inject([AuthService],(mockAuthInstance)=> {'''it('init root ...')) –

相關問題