3

I'm trying to write a test that asserts on Angular's ngModel attribute. At this point, I can easily test the label. However, I am not able to select the value from ngModel

Question What is the best way to get the value from ngModel?

HTML:

<div name="customerName">
    <label>Customer Name: </label>
    <div>
        <input type="text" class="form-control" [ngModel]="customer.name" asInline disabled />
    </div>
</div>

Test

it('bindings', () => {
    fixture = TestBed.createComponent(CustomerComponent);
    fixture.detectChanges();

    // this works
    expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] label').textContent).toEqual('Customer Name: '); 
    // this assert fails
    expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] div input').value).toEqual('Bobby Tables'); 
});
1
  • What error are you getting? Commented Mar 23, 2017 at 18:24

1 Answer 1

8

Use async together with whenStable

it('should recognize a timepicker', async(() => {
  fixture = TestBed.createComponent(ExampleComponent);
  fixture.detectChanges();

  fixture.whenStable().then(() => {
    expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] label').textContent).toEqual('Customer Name: ');

    expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] div input').value).toEqual('Bobby Tables');
  });   
}));

Plunker Example

or fakeAsync with tick:

it('should recognize a timepicker', fakeAsync(() => {
  fixture = TestBed.createComponent(ExampleComponent);
  fixture.detectChanges();
  tick();

  expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] label').textContent).toEqual('Customer Name: ');

  expect(fixture.debugElement.nativeElement.querySelector('[name=customerName] div input').value).toEqual('Bobby Tables');
}));

Plunker Example

And don't forget to import FormsModule:

TestBed.configureTestingModule({
    imports: [FormsModule],
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. Unfortunately, this doesn't resolve my problem. The .value is returning an empty string. If I log it at the [name=customerName] div input level, I get <input asinline="" class="form-control" disabled="" type="text">. I've verified, and my component has the correct data. Any other thoughts?
I've got it working, needed to add the imports: [FormsModule] to my beforeEach Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.