0

I use Angular 2 Karma-Jasmine. I have AService,

it("test", () => {
    let x:any = function1('value', aService);
    expect(x).toEqual("value1");
});

Now AService has getA() method, and function1 used getA() method. I want mock AService.getA method?.

Please tell me best ways for mocking AService ?

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
emanuel07
  • 738
  • 12
  • 27
  • Are you using dependency injection in your test? please provide a bigger example. – Supamiu Oct 04 '16 at 19:34
  • I havent example deat @Supamiu,I want learn best ways for mocking in angular2-jasmine-karma. My function1 is static,to whcih passed AServcie,there is no injection. – emanuel07 Oct 04 '16 at 19:38

1 Answers1

1

If function's signature is to accept AService type

function1(value, service: AService) {}

then you need to make sure that the mock is compatible with AService. If AService only has one method getA, then you really only need to do

let mockA = {
  getA: () => {
    // mock implementation
  }
}

If AService has more methods than just the getA and you don't want to have to implement that, then you can "cast" the mock to type AService.

let mock = <AService>{ same as above }

Or if the function1 parameter is not typed as AService, then you can really pass anything it.

See Also:

  • This post which gives an explanation about TypeScript's structural type system
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720