我想用Jest代替jasmine来为我的angular应用编写单元测试。
方法canActivate的guard服务的简单单元测试。
我的问题是,如何模拟路由器?
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。
解决方案吗?
因为您正在使用ng-mocks
,并且您想要模拟所有依赖项,例如Router
,您可以使用ng-mocks
文档如何测试提供程序。它简单地解释了如何模拟你的提供商的所有依赖:根据文档,您的测试应该如下所示:
describe('TestServiceGuard', () => {
MockInstance.scope(); // <- add to reset customizations after tests.
// Simply mock all dependencies apart from the guard.
// It will automatically mock Router and other services.
beforeEach(() => {
return MockBuilder(TestServiceGuard, TestModule)
.mock(TranslateService, {
instant: (value) => value,
});
});
it('should be created', () => {
MockInstance(TheOtherService, 'testData', jest.fn(), 'get')
.mockReturnValue(of(data));
const fixture = MockRender(TestServiceGuard);
const service = fixture.point.componentInstance;
// assertions
});
});