4

In my ANGULAR 2 application there is a service; that contains a static reference property.

export class MyService {
    public static OneProperty: ClassA;
}

And here is a sample implementation of the method I am going to test in my ts file.

export class TestComponent() {
    oneProperty: User;

    public NumberOfUsers(): string {
    this.oneProperty = MyService.OneProperty.someThing;
    return this.oneProperty;
    }
}

How can I mock the data in the static variable for the test cases? Whenever I try to mock the data in useClass/useValue format, I am getting a undefined value for MyService.OneProperty.

Prateek
  • 135
  • 3
  • 15
  • 1
    `export class TestComponent() { oneProperty: User; public string NumberOfUsers() { this.oneProperty = MyService.OneProperty.someThing; } }` ... doesn't this give you **compilation error**? Check this: https://stackblitz.com/edit/typescript-utcswj – lealceldeiro Jul 13 '18 at 15:29
  • I wrote some pseudo code here for the function NumberOfUsers – Prateek Jul 13 '18 at 16:06

1 Answers1

1

Can you please post an example of how did you try useClass/useValue?

This should work:

class MockMyService {
  public static oneProperty = 'mock';
}

Then in your tests:

describe('TestComponent', () => {
  beforeEach(() => TestBed.configureTestingModule({
    ...
    providers: [
      {provide: MyService, useClass: MockMyService},
    ]
  });

  it('should work with mock service', () => {
    const mockService = TestBed.get(MyService);
    expect(mockService.oneProperty).toEqual('mock');
  });
});

The above is just pseudo-like, I couldn't test it anywhere, but this should give you an idea.

Alex Szabo
  • 3,274
  • 2
  • 18
  • 30
  • Well! I wrote few LOC to make the MockMyService static calls. But I have the problem, when I am debugging the code in the component's method (where the reference of the Service variable is present), I am seeing undefined. Conclusion: The value of mock is not assigned to the service. – Prateek Jul 16 '18 at 07:15