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 ...')) –