Reputation: 65
I am new to unit testing in Angular. Is there any way other than this to write unit tests for this particular function? Thank you!
list-user.component.ts
constructor(private auth: AuthenticationService, private router: Router, private dialog: MatDialog) { }
fetchOfficeInfoByManager() {
this.auth.getUserbyLM().subscribe((data: User[]) => {
this.usersource = new MatTableDataSource(data);
}
ngOnInit() {`
this.fetchOfficeInfoByManager();
}
list-user.component.spec.ts
import { ListUserComponent } from './list-user.component';
import { AuthenticationService } from '../../shared/services/authentication.service';
import { Observable } from 'rxjs';
import { from } from 'rxjs'
describe ('ListUserComponent', () => {
let component: ListUserComponent;
let service: AuthenticationService;
beforeEach(() => {
service = new AuthenticationService(null, null);
component = new ListUserComponent(service, null, null);
});
it('should get employees according to line manager', () => {
let data = [];
spyOn(service, 'getUserbyLM').and.callFake(() => {
return from([ data ]);
});
component.fetchOfficeInfoByManager();
expect(component.data).toBeTruthy();
});
});
Upvotes: 2
Views: 131
Reputation: 17494
Yes, you can do :
class MockAuthService{
getUserbyLM(){
return
of({
name: 'User',
id: 'id'
})
}
}
describe('ListUserComponent',()=>{
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [modules......],
providers: [{ provide: AuthService, useClass: MockAuthService }]
}).compileComponents();
}));
it('should have usersource defined when fetchOfficeInfoByManager() is called', () => {
component.fetchOfficeInfoByManager();
expect(component.usersource).toBeDefined();
expect(component.usersource.name).toBe('User');
// and so on......
});
})
You need to add some import
for rxjs for using of()
. I hope you can get some idea about how to test that function from this example
Upvotes: 1