简体   繁体   中英

Unit testing services in Angular

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();
    });
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM