【发布时间】:2021-09-28 20:12:04
【问题描述】:
这是我的指令
@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');
});
});
前两个单元测试通过了,但是第三个却抛出了这个错误:
CORS 策略已阻止从源“http://localhost:9876”访问“ng:///TitleCaseDirective/%C9%B5dir.js”处的 XMLHttpRequest:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、chrome-untrusted、https。
我不确定这里为什么会抛出 CORS 错误。
【问题讨论】:
标签: angular angular-directive angular-unit-test