hackp0int
hackp0int

Reputation: 4161

Angular9 unit-testing: Is it possible to MOCK Parse.initialize and still have reliable tests?

I want to test component how do I do it with Parse.initialize(appId,url) function inside my Angular Service?
This is the initialization part:

Parse.initialize('MY_APP_ID', 'JS_KEY');
Parse.serverURL = 'https://parseapi.back4app.com/';

This is my test part:

describe('StateComponent', () => {
  let component: StateComponent;
  let fixture: ComponentFixture<StateComponent>;
  let service: TrayStateService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [StateComponent],
      providers: [
        TrayStateService,
        { provide: NbDialogService, useValue: {} },
        { provide: NbToastrService, useValue: {} },
        ChangeDetectorRef,
        AuthSessionQuery,
        {
          provide: 'env',
          useValue: environment
        }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
    service = TestBed.inject(TrayStateService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(StateComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should verify that immediate function works properly', fakeAsync(() => {
      spyOn(service, 'getAll').and.returnValue(of(MockedDataResponseArray));
      component.ngOnInit();
      tick(10);
  }));

This is the error I get:

Error: You need to call Parse.initialize before using Parse.

Upvotes: 0

Views: 177

Answers (1)

satanTime
satanTime

Reputation: 13584

You can provide a spy via direct assignation.

let backup: any;
beforeEach(() => {
  backup = Parse.initialize;
  Parse.initialize = jasmine.createSpy();
});
afterEach(() => Parse.initialize = backup);

// ... your normal code

it('in a test', () => {
  // ... your normal code
  expect(Parse.initialize).toHaveBeenCalledWith('MY_APP_ID', 'JS_KEY');
  expect(Parse.serverURL).toEqual('https://parseapi.back4app.com/');
});

Upvotes: 1

Related Questions