测试Angular组件

时间:2017-04-19 15:40:35

标签: javascript angular testing jasmine

我试图用Jasmine测试我的Angular组件。该组件是一个简单的表单,它将一些搜索条件提交给服务,然后该服务关闭并执行Http并返回实体数组。

我正在使用Jasmine来窥探' spyOn'服务方法然后返回一个模拟实体。然后,应将此模拟实体保存在组件中的变量中。

我面临的问题是,当我断言实体已成功返回时,我在实体变量中未定义,这让我觉得我没有正确设置我的间谍或类似的东西。

任何帮助将不胜感激!

服务:

@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未定义。

1 个答案:

答案 0 :(得分:1)

您正在使用异步代码Promise。将expect放入fixture.whenStable func并将async函数添加到'it'单元测试中。

function onLoad() {
    var items = $$('BUTTON').each(function(item){
        if(item.innerHTML.indexOf('Save') > -1){
            item.hide();
        }
    });
}