【发布时间】:2019-02-03 16:45:20
【问题描述】:
我正在运行一个简单的测试 - 在 Ionic 搜索栏中输入一个值。 我无法在我的 jasmine 测试中获得对搜索栏输入字段的引用。
我已经设置了一个带有单个测试页面的简单的香草 Ionic 4 应用程序。 以下测试均失败。
const el: HTMLElement = fixture.nativeElement;
const input = el.querySelector('input');
expect(input).not.toBeNull(); // FAILS
const bar = el.querySelector('ion-searchbar');
expect(bar.innerHTML).not.toEqual(''); // FAILS
expect(bar.shadowRoot).not.toBeNull(); // FAILS
我不明白为什么? 我已经在 Ionic 列表上成功编写了其他测试来读取值。 我尝试放入计时器以给组件时间来呈现 html。 如果我在页面上放置一个简单的 HTML 输入字段,它就可以被选中。 我认为 shadow DOM 可能与此处相关,即使当我检查浏览器中的输入字段时它似乎不在 shadow DOM 中,并且标准 document.querySelector 工作正常。
HTML 页面
// test.page.html
<ion-header>
<ion-toolbar>
<ion-title>
Test Page
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-searchbar></ion-searchbar>
</ion-content>
组件类
// test.page.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.page.html',
styleUrls: ['./test.page.scss'],
})
export class TestPage {
constructor() { }
}
测试规范
// test.page.spec.ts
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TestPage } from './test.page';
describe('TestPage', () => {
let component: TestPage;
let fixture: ComponentFixture<TestPage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ TestPage ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestPage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have a searchbar', () => {
const el: HTMLElement = fixture.nativeElement;
const bar = el.querySelector('ion-searchbar');
fixture.detectChanges();
expect(bar).not.toBeNull(); // PASSES
// adding some checks to see what is going on
expect(bar.children.length).toBeGreaterThan(0); // FAILS
expect(bar.innerHTML).not.toEqual(''); // FAILS
expect(bar.shadowRoot).not.toBeNull(); // FAILS
});
it('should have an input field', () => {
const el: HTMLElement = fixture.nativeElement;
const input = el.querySelector('input');
expect(input).not.toBeNull(); // FAILS
});
});
【问题讨论】:
标签: ionic-framework jasmine ionic4