私は角度2のコンポーネントのプロパティが約束を返すサービス呼び出しの後に設定されていることを確認するための単体テストを作成しようとしています。リモートエンドポイント - テスト構文の代わりにローカルjson-serverを呼び出すサービスを偽装しましたか? (角2)
私のコンポーネントは、メソッドが含まれています
@Injectable()
export class EmployeeService {
constructor(
public http: Http
) { }
\t \t
public loadEmployees(): Promise<any> {
return this.http.get('employees.json')
.map((res: Response) => res.json())
.toPromise();
}
}
つかむ:サービスのメソッドを呼び出す
getListItems() {
this.employeeService.loadEmployees().then(res => {
this._employees = res['Employees'];
this.ref.markForCheck();
});
};
ローカルのjsonファイルからのコンテンツ(リモートエンドポイントを作成する代わりに)これで十分ですが、ローカルのjson-serverを呼び出すメソッドを使ってテストするときに、サービスメソッドを置き換えたいと思います。
カルマテストの実行中にjson-serverが正しく回転/停止していることがわかりました。テストの実行中にPostmanを使用してGETリクエストを正常に実行できます。
従って私はモックと私のサービスを置き換えるしたいと思います:
class MockEmployeeService {
headers: Headers;
constructor(private http: Http) {
this.headers = new Headers({ 'Content-Type': 'application/json' });
}
public loadEmployees() {
return this.http.get('http://localhost:3004/getEmployees',
{headers: this.headers, body: '' })
\t .map((res: Response) => res.json());
\t }
}
と、次のように私はユニットテストを設定している:
describe('ListComponent',() => {
let fixture;
let component;
let employeeService;
beforeEach(async(() => {
\t TestBed.configureTestingModule({
\t imports: [
\t \t HttpModule
\t ],
\t declarations: [
\t \t ListComponent
\t ],
\t providers: [
\t {provide: EmployeeService, useClass: MockEmployeeService}
\t ]
})
.compileComponents();
}));
beforeEach(() => {
\t fixture = TestBed.createComponent(ListComponent);
\t component = fixture.componentInstance;
\t employeeService = fixture.debugElement.injector
.get(EmployeeService);
\t });
it('should retrieve test values from json-server (async)',
async(() => {
\t fixture.detectChanges();
\t component.getListItems();
\t fixture.whenStable.then(() => {
\t \t expect(component._employees).toBeDefined();
\t });
}));
})
だから私はサービスを呼び出すコンポーネントのメソッドを呼び出しています。これはMockEmployeeService
に置き換えてください。
× should retrieve test values from json-server (async)
PhantomJS 2.1.1 (Windows 7 0.0.0)
Failed: Can't resolve all parameters for MockEmployeeService: (?).
私はこの時点で私の知識の境界でかなりのだと私はトラブル新しい、テストベッド-使用してテスト用のオンラインリソースを見つけることを抱えている:私は、次のカルマのエラーを取得します。外に見えるものは誰でも見つけられますか?
ありがとうございました。 – dgkane