Search code examples
angularunit-testingtestingangular2-changedetection

Input value does not change after changeDetection() in Angular unit test


I use this component code:

HTML:

<app-input [model]="model" field="name"></app-input>

TypeScript:

@Component({
  selector: 'app-post-create-edit',
  templateUrl: './post-create-edit.component.html',
  styleUrls: ['./post-create-edit.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PostCreateEditComponent {
  model: new Post();
}

In my spec.ts file:

describe('PostCreateEditComponent', () => {
  let fixture: ComponentFixture<PostCreateEditComponent>;
  let component: PostCreateEditComponent;
  const datas = POSTS_CREATE_EDIT_DATASET;
  const model: PostInterface = new Post([datas[0]);

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [...],
      providers: [...],
      declarations: [PostCreateEditComponent]
    })
    .compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(PostCreateEditComponent);
      component = fixture.componentInstance;
      debugElement = fixture.debugElement;
      component.model = model;
      fixture.detectChanges();
    });
  });

  describe('general', () => {
    it('create-edit component test', () => {
      fixture.whenStable().then(() => {
        const container = context.debugElement
          .queryAll(By.css(`app-input[field="name"]`));
        const input = container[0].queryAll(By.css(context.input.type));

        expect(input[0].nativeElement.value).toEqual(model.name);
      });
    });
  });
});

And it says Error: "name" input element: Expected 'First post title' to equal ''.

I don't understand why doesn't changed the input field's value after call changeDetection().

How can I solve this issue? What I miss?


Solution

  • I think the problem is backwards from what you think it is. Jasmine assertions give the "found" value first and the expected value second. It's expecting '' but finding 'First post title'.

    I think. Jasmine assertion responses always get me mixed up ^^