简体   繁体   中英

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?

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 ^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM