在Angular 16中使用inject()方法为简单的Angular函数编写单元测试

问题描述 投票:0回答:1

Angular CanActivate 接口被弃用后,我根据官方文档更改了对简单 const 函数的保护。 例如,这是我的 inverseAuthGuard 方法,它似乎工作正常:

export const inverseAuthGuard = (): boolean => {
  const authService = inject(AuthService);
  const router = inject(Router);
  if (authService.isAuthenticated()) {
    router.navigate(['/visual-check']);
    return false;
  }
  return true;
};

我的问题是,我想为其编写一些单元测试,但我不知道如何将模拟 authService 和模拟路由器注入到该函数中。我看过这个 video,它解释了如何将模拟服务注入到类中,但对于我的防护功能,我无法使其工作。

我尝试了一些方法,但找不到任何解决方案。 如果我这样做:


describe('InverseAuthGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      providers: [
        { provide: AuthService, useValue: AuthService },
        { provide: Router, useValue: Router },
      ],
    });
  });

  fit('should return true on not authenticated user', () => {
    const result = inverseAuthGuard();
    expect(result).toBe(true);
  });
});

我遇到以下错误:

NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`

如果我这样做,我在视频中看到的:

describe('InverseAuthGuard', () => {
  const setupWithDI = (authService: unknown, router: unknown) =>
    TestBed.configureTestingModule({
      providers: [
        { provide: AuthService, useValue: authService },
        { provide: Router, useValue: router },
      ],
    }).inject(inverseAuthGuard);

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
    });
  });

  fit('should return true on not authenticated user', () => {
    const mockAuthService: unknown = { isAuthenticated: () => true };
    const mockRouter: Router = jasmine.createSpyObj(['navigate']);
    setupWithDI(mockAuthService, mockRouter);
    const result = inverseAuthGuard();
    expect(result).toBe(true);
  });
});

我遇到以下错误:

NullInjectorError: No provider for inverseAuthGuard!

当然,我尝试过以某种方式提供 inverseAuthGuard,但没有成功。 我认为应该有一个简单的解决方案,但我没有在任何文档中找到。我将不胜感激任何答案。

angular unit-testing dependency-injection karma-jasmine angular16
1个回答
0
投票

您可以使用旧的设置在正确的注入上下文中运行函数

const result = TestBed.runInInjectionContext(() => inverseAuthGuard());
© www.soinside.com 2019 - 2024. All rights reserved.