我想用Jest而不是Jasmine来为我的angular应用程序编写一个单元测试。
方法canActivate的防护服务的模拟单元测试。
我的问题是,如何模拟路由器?
describe('TestServiceGuard', () => {
let service: testServiceGuard;
let router: Router;
beforeEach(() => {
return MockBuilder(TestServiceGuard, TestModule)
.mock(TranslateService, {
instant: (value) => value,
})
.mock(Router)
});
it('should be created', () => {
mockCurrentData(data);
const fixture = MockRender
});
//this mehtod mock a servcie, which will be called in method canActivate.
function mockCurrentData(fleet: Fleet): jest.Mock {
return MockInstance(<the other servcie>, 'testData', jest.fn(), 'get') //
.mockReturnValue(of(data));
}
// I just wannt to mock Router, but I do not know how?
function mockRouter(){
const router = new Mockr
}
//then
function rediretToExpectedSite(){
expect();
}
});
我亦看到一些例子,例如
it('should navigate to home for a logged out user', () => {
authService = { isLoggedIn: () => false };
router = new MockRouter();
authGuard = new AuthGuard(authService, router);
spyOn(router, 'navigate');
expect(authGuard.canActivate()).toEqual(false);
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
但在我的玩笑测试中没有MockRouter。
有什么解决办法吗?
1条答案
按热度按时间gojuced71#
因为您使用的是
ng-mocks
,并且希望模拟所有依赖项,例如Router
,所以可以使用ng-mocks
documentation how to test a provider。它简单地解释了如何模拟提供程序的所有依赖项:那个警卫。根据文档,您的测试应如下所示: