0

This is my directive

@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) {}
}

and this is my test

@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');
  });
});

the first two unit tests are passing, but the 3rd one is throwing this error:

Access to XMLHttpRequest at 'ng:///TitleCaseDirective/%C9%B5dir.js' from origin 'http://localhost:9876' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

I'm not sure why CORS error is thrown here.

rene
  • 41,474
  • 78
  • 114
  • 152
nshathish
  • 417
  • 8
  • 23

1 Answers1

0
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');
  });
nshathish
  • 417
  • 8
  • 23