【问题标题】:Unit testing services in AngularAngular 中的单元测试服务
【发布时间】:2019-02-03 04:55:50
【问题描述】:

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

【问题讨论】:

    标签: angular unit-testing


    【解决方案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()。我希望你能从这个例子中了解如何测试这个函数

    【讨论】:

    • 我应该导入 list-user-component @Shashank Vivek 中使用的所有模块吗?
    • @NileshMaharjan:是的。尝试运行它,你会得到错误并逐步修复它。我相信您已经为您在问题中提供的示例修复了它。我对导入的建议是针对of(),我在MockAuthService中使用过
    • 谢谢!有效。你也可以签到stackoverflow.com/questions/54546332/… 吗?
    • @NileshMaharjan 将其标记为答案并投票支持 SO 社区和我。如果其他人遇到类似问题,这将有助于其他人选择此解决方案。
    猜你喜欢
    • 2019-05-06
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 2017-12-20
    • 1970-01-01
    相关资源
    最近更新 更多