The error is likely due to the fact that you have not initialized the variable token
. When setting up a mock for a service in a component test, it is often sufficient to create spies for the functions that will be called. Testing whether the component calls these functions is crucial. Additionally, you need to replace the actual service with the mock service by configuring the mock as a provider substitute. Here's an example:
@Component({
...
})
class TestComponent {
constructor(private token: Angular2TokenService) {}
ngOnInit() {
token.init();
}
onLogin(email, password) {
token.signIn(email, password);
}
}
describe('..', () => {
let tokenStub;
let component;
let fixture;
beforeEach(() => {
tokenStub = {
init: jasmine.createSpy('init'),
signIn: jasmine.createSpy('signIn')
}
TestBed.configureTestingModule({
declarations: [ TestComponent ],
providers: [{ provide: Angular2TokenService, useValue: tokenStub }]
})
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
})
it('should initialize the token when the component is created', () => {
fixture.detectChanges();
expect(tokenStub.init).toHaveBeenCalled();
})
it('should sign in with the token when logging into the component', () => {
component.onLogin();
expect(tokenStub.signIn).toHaveBeenCalledWith('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9beffee8efdbfef6faf2f7b5f8f4f6">[email protected]</a>', 'foobar')
})
})
In the tests, we verify that the functions are called using the toHaveBeenCalledXxx
methods, which can accept arguments.
If you prefer to run an isolated test without using the TestBed
configuration, you can easily achieve this by:
let tokenStub: Angular2TokenService;
let component;
beforeEach(() => {
tokenStub = {
init: jasmine.createSpy('init'),
signIn: jasmine.createSpy('signIn')
} as Angular2TokenService;
component = new TestComponent(tokenStub);
})
it('..', () => {
component.ngOnInit();
expect(tokenStub.init).toHaveBeenCalled();
})
Don't forget to refer to the spy documentation linked above for more advanced functionalities, such as returning specific values.