2017-08-02 131 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 ...')) –