2017-05-08 2 views
1

큰 프로젝트를 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; 
    } 
} 

당신에게 사이먼

답변

1

먼저 대단히 감사합니다,이

public loadConfiguration(isUnitTest: boolean = false): Promise<any> { 
    return new Promise((resolve, reject) => { 
     if (isUnitTest) { 

단위 테스트는이 같은 구현의 세부 사항을 누설해서는 안 나쁜 생각이다. 무엇 해야합니까 그냥 구성 데이터를 조롱입니다.

import { mockConfigData } from './whereever'; 

... 
const config = new FieldConfigurationService(); 
config.config = mockConfigData; 

providers: [ 
    { provide: FieldConfigurationService, useValue: config } 
] 

그래서 모의 파일이있는 위치에서 일부 모의 데이터를 사용하도록 서비스를 설정했습니다. 이제 당신이해야 할 것은 null 해결의 요점은 무엇 resolve(null)

if (!this.config) { 
    ... 
} else { 
    resolve(null); 
} 

을 수정 프로그램입니다. 이 논리의 요점은 "설정이 없으면 가져오고 그렇지 않으면 반환 null". "그렇지 않으면 config를 반환"하지 않아야합니까? 그래서 고쳐주세요. 당신은 내가보기 엔 당신이 제안 것 isUnitTest 쓰레기를 제거하지 않는 한, 시험에 아무것도 변경할 필요가 없습니다 있도록이 설정이와

if (!this.config) { 
    ... 
} else { 
    resolve(this.config); 
} 

를 해결 확인, 약속은, 동 기적으로 해결.

+0

하하하 ... 고맙습니다. 유닛 테스트에 너무 집중하여 FieldConfigurationService를 완전히 무시했습니다. 그것은 당신의 의견 덕분에 지금 작동합니다. –