emanuel07
emanuel07

Reputation: 758

Angular2 mocking injectable service

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 ?

Upvotes: 0

Views: 307

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208994

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

Upvotes: 1

Related Questions