Angular2测试(茉莉花)嘲笑服务。无法解析服务的所有参数:(?,?)

时间:2017-10-26 15:25:05

标签: angular testing mocking

我正在尝试模拟以下服务来测试我的组件:

生产:

@Injectable()
export class UserService extends DtoService {
    // some not relevant stuff.
}

@Injectable()
export abstract class DtoService {
    constructor(private http: Http, private authHttp: AuthHttp) {}

    get() {
        return this.http.get(...);
    }
}

@Component({
    selector: 'users',
    templateUrl: 'users.component.html',
    styleUrls: ['users.scss'],
    providers: [UserService]
})
export class UsersComponent implements OnInit, OnDestroy {
    constructor(private userService: UserService) {}
    // etc
}

测试:

class MockUserService {
    public get(): Observable<User> {
        return Observable.of(new User({id: 1, email: 'user1@test.com'}));
    }
}

beforeEach(async(() => {

    TestBed
        .configureTestingModule({
            declarations: [UsersComponent],
            providers: [{provide: UserService, useClass: MockUserService}]
        });
    this.fixture = TestBed.createComponent(UsersComponent);

}));

它应该是最经典的用例,对(见angular test doc)?但在这里我得到错误:

Can't resolve all parameters for UserService: (?, ?).

但是UserService根本不应该被实例化。我究竟做错了什么? 谢谢社区!

1 个答案:

答案 0 :(得分:0)

你必须在你的存根服务的构造函数private http: Http, private authHttp: AuthHttp或它的一些模拟服务中提供。