큰 프로젝트를 4 각도로 작업 중입니다. 서버에서 JSON 데이터를 가져온 다음 클라이언트의 특수 테이블 구성 요소에 해당 데이터를 표시합니다.재 스민 테스트 전에 구성로드 중
테이블의 특기는 표시되는 열을 클라이언트 측에서 정의 할 수 있다는 것입니다. 어떤 컬럼이 있는지 알아 내려면 서버에서 구성 JSON 파일을 가져와야합니다. 그리고 우리는이 일을 한 번만하기 때문에 모듈이로드되기 전에로드 메커니즘을 가드에 배치했습니다. 지금까지이 잘 작동합니다.
- 는
- 는 서버에서 데이터를 가져 오기 테이블을 채우기 가드의 열 선언을 가져 오기 : 나는이 개 요청을해야합니다. 구성 요소에서 완료되었습니다.
이제 이것을 테스트해야합니다. 그리고 그것이 내 문제가 시작되는 곳입니다. jasmine이 단위 테스트를 실행하기 전에 JSON 요청 열을 가져올 수 없습니다.
fdescribe('Component: MyComponent',() => {
let fixture: ComponentFixture<MyComponent>;
let component: MyComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
providers: [
FieldConfigurationService
],
schemas: [NO_ERRORS_SCHEMA],
imports: [
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, 'resources/i18n', '.json'),
deps: [Http]
})
]
}).overrideComponent(MyComponent, {
set: {
providers: []
}
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
}));
it('should create an instance',() => {
expect(component).toBeTruthy();
});
describe('when field Configuration is loaded',() => {
beforeEach(async(() => {
console.log(1);
component.fieldConfigurationService.loadConfiguration(true);
console.log(2);
}));
describe('when the component is ready for use',() => {
console.log(3);
});
});
});
console.log의 출력은 3,1,2입니다.
어떻게하면 component.fieldConfigurationService.loadConfiguration();을 배치해야합니까? 명령을 사용하여 console.log (3)가 시작된 블록 앞에서 실행되도록합니다.
또한 테스트 베드의 "다음"섹션에도 삽입하려고했습니다. 지금까지 내가 한 모든 작업은 데이터로드 프로세스의 비동기 특성으로 인해 서버에서 데이터가로드되기 전에 항상 단위 테스트 실행이 시작되었습니다.
아무런 도움이 필요하지 않습니다.
FieldConfigurationService는 다음과 같습니다.
@Injectable()
export class FieldConfigurationService {
public config: any = {};
public loadConfiguration(isUnitTest: boolean = false): Promise<any> {
return new Promise((resolve, reject) => {
if (isUnitTest) {
if (!this.config) {
this.config = this.readJSON('base/gulpdist/field-definition.json');
resolve(this.config);
} else {
resolve(null);
}
} else {
if (!this.config) {
this.getJSON().subscribe(
data => {
this.config = data;
resolve(data);
},
error => reject(error)
);
} else {
resolve(null);
}
}
});
}
}
private readJSON(url) {
let xhr = new XMLHttpRequest();
let json = null;
xhr.open('GET', url, false);
xhr.onload = function (e) {
if (xhr.status === 200) {
json = JSON.parse(xhr.responseText);
} else {
console.error('readJSON', url, xhr.statusText);
}
};
xhr.onerror = function (e) {
console.error('readJSON', url, xhr.statusText);
};
xhr.send(null);
return json;
}
}
당신에게 사이먼
하하하 ... 고맙습니다. 유닛 테스트에 너무 집중하여 FieldConfigurationService를 완전히 무시했습니다. 그것은 당신의 의견 덕분에 지금 작동합니다. –