簡體   English   中英

測試Angular組件時的Jasmine spyOn服務

[英]Jasmine spyOn service when testing Angular component

我正在嘗試用Jasmine測試我的Angular組件。 該組件是一種簡單的表單,向服務提交一些搜索條件,然后該服務關閉並執行Http填充並返回實體數組。

我正在使用Jasmine來'spyOn'服務方法,然后返回一個模擬實體。 然后,應將此模擬實體保存在組件中的變量中。

我面臨的問題是,當我斷言該實體已成功返回時,我在entities變量中變得未定義,這使我覺得我沒有正確設置間諜程序或類似的東西。

任何幫助將不勝感激!

服務:

@Injectable()
export class DynamicsSearchService {
    private apiUrl = '/api/DynamicsSearch/Search';
    private headers = new Headers({ 'Content-Type': 'application/json' });

    constructor(private http: Http) { }

    search(search: DynamicsSearch): Promise<any[]> {
        search.fields = this.getDefaultFields(search.entity);
        return this.http
            .post(this.apiUrl, JSON.stringify(search), { headers: this.headers })
            .toPromise()
            .then((response) => { return this.extractResults(search.entity, response.json()); })
            .catch(this.handleError);
    }

    ...
}

零件:

@Component({
    selector: 'dynamics-search-component',
    templateUrl: 'dynamics-search.component.html'
})
export class DynamicsSearchComponent {
    ...

    entities: any[];

    constructor(private searchService: DynamicsSearchService) { }

    submitSearch() {
        this.searching = this.searched = true;
        this.searchService.search(this.model)
            .then(results => {
                this.entities = results;
                this.searching = false;
                this.searchSuccessful = results !== null && results.length > 0;
            });
    }

    ...
}

測試:

describe('DynamicsSearchComponent', () => {

    let fixture: ComponentFixture<DynamicsSearchComponent>;
    let component: DynamicsSearchComponent;

    let configuration = new Configuration();

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                FormsModule,
                SharedModule
            ],
            providers: [
                BaseRequestOptions,
                MockBackend,
                DynamicsSearchService,
                Configuration,
                {
                    provide: Http,
                    useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
                        return new Http(backend, defaultOptions);
                    },
                    deps: [
                        MockBackend,
                        BaseRequestOptions
                    ]
                }
            ],
            declarations: [
                DynamicsSearchComponent
            ]
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(DynamicsSearchComponent);
        component = fixture.componentInstance;
    });

    it('on submit should get a single contact',
        inject([DynamicsSearchService], (service: DynamicsSearchService) => {
            var expected = [
                {
                    contactid: 'A7806F57-002C-403F-9D3B-89778144D3E1'
                }
            ];

            const spy = spyOn(service, 'search')
                .and.returnValue(Promise.resolve(expected));            

            component.model = new DynamicsSearch('contacts', 'A7806F57-002C-403F-9D3B-89778144D3E1', null, 'contactid');
            component.submitSearch();

            fixture.detectChanges();

            expect(spy.calls.count()).toBe(1, `expected service search method to be called once but was called ${spy.calls.count()} times`);
            expect(component.entities).toBeDefined('no entities returned');
            expect(component.entities.length).toBe(1, `expected 1 entity to be returned but only ${component.entities.length} were returned`);
        }
    ));
});

由於component.entities未定義,因此它在第二個期望值上失敗。

您正在使用異步代碼Promise。 將Expect放入fixture.whenStable函數中,並將異步函數添加到“ it”單元測試中。

fixture.whenStable().then(() => {
    expect(component.entities).toBeDefined('no entities returned');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM