angular - 运行 Angular e2e 测试时如何禁用或绕过 MSAL 身份验证?

标签 angular angular-cli e2e-testing msal angular-e2e

我想为我的 Angular 应用程序设置一些端到端测试,这需要使用 MSAL 库对一些下游服务进行身份验证。当我尝试在本地运行我的 e2e 测试时,MSAL 库强制我使用用户名/密码进行身份验证。

这是一个问题,因为我们的 CI/CD e2e 测试不应该有任何人为干预;因此,我正在寻找一种绕过 MSAL 身份验证或设置服务帐户登录的方法。不幸的是,关于 Angular 的 MSAL 的文档并不多(尤其是在 e2e 测试方面),但这似乎是其他人可能遇到的常见问题。

我试图从我们的 app.module.ts 文件中禁用 MsalModule,但是当我尝试运行应用程序时,仍然提示我登录。我还看到一些试图以编程方式登录的文章,但这对我们不起作用,因为 MSAL 在技术上不是我们能够接触到的 Angular 组件。

app.module.ts:

@NgModule({
  ...
  imports: [
    ...
    MsalModule.forRoot({
      clientID: '<client_id>',
      authority: <microsoft_authority_url>,
      validateAuthority: true,
      redirectUri: "http://localhost:4200/",
      cacheLocation : "localStorage",
      postLogoutRedirectUri: "http://localhost:4200/",
      navigateToLoginRequestUrl: true,
      popUp: true,
      consentScopes: [ "user.read"],
      unprotectedResources: ["https://www.microsoft.com/en-us/"],
      protectedResourceMap: protectedResourceMap,
      logger: loggerCallback,
      correlationId: '1234',
      level: LogLevel.Info,
      piiLoggingEnabled: true
    })
  ],
  entryComponents: [SaveDialogComponent,
                    GenericDialog, MassChangeDialogComponent],
  providers: [TitleCasePipe,
    {provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true}],
  bootstrap: [AppComponent]
})
export class AppModule { }

预期结果:删除 MSAL 身份验证模块应该允许我们的应用程序无需登录即可运行。

实际结果:应用程序仍在提示登录,或未正确呈现。

最佳答案

我通过添加属性 enableMsal 解决了这个问题进入我的 environment.test.ts (以及在 prod 环境中具有值 true 的相同属性):

export const environment = {
  production: false,
  enableMsal: false,
};

然后在路由模块中使用它(默认称为app-routing.module.ts,像这样:
//... 
const guards: any[] = environment.enableMsal ? [MsalGuard] : [];

const routes: Routes = [
  {path: '', redirectTo: '/main', pathMatch: 'full'},
  {path: 'main', component: MainComponent, canActivate: guards},
  {path: 'other', component: OtherComponent, canActivate: guards},
];
//...

如果您不知道如何配置多个环境,Angular 有一个很好的指南 here .

关于angular - 运行 Angular e2e 测试时如何禁用或绕过 MSAL 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56600532/

相关文章:

javascript - Angular2 表在过滤后无法正确构建

javascript - Angular2 - RadioButtonState 没有按预期工作

node.js - 找不到模块@angular\cli\bin\ng

angular - PostCSS 插件出现未知错误..可能是错误

angular - e2e如何在 Angular Protractor 中测试登录成功案例

javascript - 自动完成不过滤列表项 Angular

angular - 是否可以在代码中使用管道?

angular - 模块构建失败 : SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"'

cypress - 如何让 cypress 等待依赖于另一个响应的响应?

automated-tests - testcafe 是否支持 pressKey ("shift+enter")?