ReferenceError: FB not defined in Angular 5 Karma Unit Test

I have this problem when I have karma unit test.

Error screenshot

Failed: Unprepared (in promise): ReferenceError: FB not defined

I already added the following script in the index.html file:

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

This is my file 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);
  }

When I do unit test, the file https://connect.facebook.net/en_US/sdk.jsdoes not load at all.

How can I fix this problem?

Thank.

+4
source share
1 answer

First, you need to load the external javascript file into the Karma validator by adding filesconfig to karma.config.js, as shown below:

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

And then make sure your test is NOT IN 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();
  }));

, .

+3

Source: https://habr.com/ru/post/1690474/


All Articles