1

I am trying to test this service. As you can see, mixpanel is not an injected service. It is an imported namespace.

import * as mixpanel from 'mixpanel-browser';

@Injectable({
   providedIn: 'root',
})
export class MixpanelService {
  constructor() {
    mixpanel.init('xxxxxxxx');
  }

  public register(value: string): void {
     mixpanel.register(value);
  }

}

describe('MixpanelService', () => { let service: MixpanelService;

 beforeEach(async() => {
   TestBed.configureTestingModule({
     providers: [
       //mixpanel is not an injected service...
     ]
   });
   service = TestBed.inject(MixpanelService);
 });

 it('should call register method', () => {
    //Arrange
    let mockMixPanel = ??? //how to mock a namespace????
    let spyOnRegister = jest.spyOn(mockMixPanel, 'register');

    //Act
    service.register({});

    //Assert
    expect(spyOnRegister).toHaveBeenCalled();
   });
  }

Thanks for helping

Richard77
  • 20,343
  • 46
  • 150
  • 252
  • 1
    It is good that you are using jest because it should be possible. I am not that good with jest but I remember being able to do it with `jest.mock`. This link (https://stackoverflow.com/a/52118844/7365461) should help you get started but you basically have to mock the npm module. – AliF50 Apr 28 '21 at 19:24

0 Answers0