【问题标题】:ReferenceError: FB is not defined in Angular 5 Karma Unit TestReferenceError:FB 未在 Angular 5 Karma 单元测试中定义
【发布时间】:2017-12-09 08:20:45
【问题描述】:

我在进行业力单元测试时遇到了这个问题。

Error Screenshot

失败:未捕获(承诺中):ReferenceError:FB 未定义

我已经在 index.html 文件中添加了以下脚本:

<script type="text/javascript" src="https://connect.facebook.net/en_US/sdk.js"></script>

这是我的auth.service.ts 文件。

constructor(
    private http: HttpClient,
    private fb: FacebookService
  ) {
    this.token = localStorage.getItem('token');

    if (this.token) this.isLoggedIn = true;
    else this.isLoggedIn = false;

    let initParams: InitParams = {
      appId: environment.FACEBOOK_APP_ID,
      xfbml: true,
      version: 'v2.8'
    };

    fb.init(initParams);
  }

当我进行单元测试时,https://connect.facebook.net/en_US/sdk.js 文件根本没有加载。

我该如何解决这个问题?

谢谢。

【问题讨论】:

  • 这是我在 index.html 文件中添加的脚本代码。
  • 这个脚本文件是加在主JS文件上面的吗,即这个文件应该在调用FB对象之前添加。
  • 请添加您在问题中遇到的错误。人们不经常关注图片链接。
  • 您好,Marcel50506 感谢您的回复。这是错误。失败:未捕获(承诺):ReferenceError:未定义FB
  • 嗨,拉利特 Sachdeva。感谢您的回复。 JS 文件添加在 index.html 文件中的

标签: angular karma-jasmine


【解决方案1】:

首先您需要通过在karma.config.js 中添加files 配置来将外部javascript 文件加载到Karma 测试环境中,如下所示:

files: [
      'https://connect.facebook.net/en_US/sdk.js'
    ],
crossOriginAttribute: false,

然后确保您的测试在不在async模式下执行。

所以通常情况下,测试是在异步模式下进行的,如下所示:

it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

只需删除async,使其如下所示:

it('should create the app', (() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 2015-06-29
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多