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);
});
});
嗨傑森,問題是,我沒有在這個範圍內的mockAuthInstance。我測試app.component.ts,內部注入AuthService。 在這個範圍內,我只有comp和fixture變量。我將編輯主要問題並添加完整的代碼示例。謝謝! – eneoes
這就是'inject()'方法的作用。他們會將相同的事情注入到你的測試中。在上面的兩個例子中,在測試名稱後面有[inject([AuthService],(mockAuthInstance)=> {'''it('init root ...')) –