如何使用Jest编写canActivate Angular guards的单元测试

mbjcgjjk  于 2022-12-20  发布在  Jest
关注(0)|答案(1)|浏览(180)

我想用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。
有什么解决办法吗?

gojuced7

gojuced71#

因为您使用的是ng-mocks,并且希望模拟所有依赖项,例如Router,所以可以使用ng-mocks documentation how to test a provider。它简单地解释了如何模拟提供程序的所有依赖项:那个警卫。
根据文档,您的测试应如下所示:

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
  });
});

相关问题