这是我的指令
@Directive({
selector: '[appTitleCase]',
})
export class TitleCaseDirective {
@HostListener('change', ['$event']) onChange($event: Event) {
const titleCaseValue = TextHelpers.convertToTitleCase(
($event.target as HTMLInputElement).value,
);
if (this.el.nativeElement.children.length > 0) {
(this.el.nativeElement.children[0] as HTMLInputElement).value =
titleCaseValue;
} else {
(this.el.nativeElement as HTMLInputElement).value = titleCaseValue;
}
// must create an "input" event, if not, there are no change in your value (though ui is changed)
const evt = document.createEvent('Event');
evt.initEvent('input', false, true);
$event.target.dispatchEvent(evt);
}
constructor(private el: ElementRef) {}
}
这是我的测试
@Component({
template: `
<div>
<input id="txt" type="text" appTitleCase />
</div>
<div appTitleCase id="txtInput">
<input type="text" />
</div>
`,
})
class TestTitleCaseComponent {}
describe('TitleCaseDirective', () => {
let fixture: ComponentFixture<TestTitleCaseComponent>;
let el: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestTitleCaseComponent, TitleCaseDirective],
});
fixture = TestBed.createComponent(TestTitleCaseComponent);
el = fixture.debugElement;
});
it('should convert the text input value to title case when the input element has the directive', () => {
const inputEl = el.query(By.css('#txt')).nativeElement;
inputEl.value = 'hello';
inputEl.dispatchEvent(new Event('change'));
expect(inputEl.value).toEqual('Hello');
});
it('should convert the text input value to title case when the parent has the directive', () => {
const parentEl = el.query(By.css('#txtInput')).nativeElement;
const inputEl = parentEl.children[0];
inputEl.value = 'hello';
parentEl.dispatchEvent(new Event('change'));
console.log(inputEl.value);
// expect(inputEl.value).toEqual('Hello');
});
});
前两个单元测试通过了,但第三个单元测试抛出了这个错误:
从原点访问'ng:///TitleCaseDirective/%C9%B5dir.js'处的XMLHttpRequesthttp://localhost:9876'已被CORS策略阻止:跨源请求仅支持以下协议方案:http、data、chrome、chrome扩展、chrome不可信、https
我不确定这里为什么会抛出CORS错误。
it('should convert the text input value to title case when the parent has the directive', () => {
const parentEl = el.query(By.css('#dlgInput')).nativeElement;
const inputEl = parentEl.children[0];
inputEl.value = 'hello';
inputEl.dispatchEvent(new Event('change', { bubbles: true }));
expect(inputEl.value).toEqual('Hello');
});