Angular中的单元测试服务

时间:2019-02-03 04:55:51

标签: angular unit-testing

我是Angular单元测试的新手。除此之外,还有其他方法可以为此特定功能编写单元测试吗?谢谢!

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

1 个答案:

答案 0 :(得分:1)

是的,您可以这样做:

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......

    });

})

您需要为rxjs添加一些import才能使用of()。我希望您可以从本示例中获得有关如何测试该功能的一些想法