简体   繁体   English

Angular 中的单元测试服务

[英]Unit testing services in Angular

I am new to unit testing in Angular.我是 Angular 单元测试的新手。 Is there any way other than this to write unit tests for this particular function?除了这个,还有什么方法可以为这个特定的函数编写单元测试吗? Thank you!谢谢!

list-user.component.ts列表-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列表-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() .您需要为 rxjs 添加一些import以使用of() I hope you can get some idea about how to test that function from this example我希望你能从这个例子中得到一些关于如何测试这个函数的想法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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