首页 > 解决方案 > 角度单元测试道具永远不会未定义

问题描述

我不明白为什么这个简单的测试实际上不起作用。

BannerComponent should not have welcome message after construction
Expected 'welcome' to be undefined.

// 零件

@Component({
  selector: 'iwdf-banner',
  template: `
    <p>
      {{me}}
    </p>
  `,
  styles: []
})
export class BannerComponent implements OnInit {
  me: string;
  constructor() { }
  ngOnInit() {
    this.me = 'welcome';
  }
}

// 测试

describe('BannerComponent', () => {
  let component: BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BannerComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BannerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should not have welcome message after construction', () => {
    expect(component.me).toBeUndefined();
  });

  it('should welcome logged in user after Angular calls ngOnInit', () => {
      component.ngOnInit();
      expect(component.me).toContain('welcome');
  });
});

标签: angularunit-testing

解决方案


好吧,TestBed 确实运行了所有必要的生命周期钩子来检测变化。因此,可以预期该变量已定义。不要使用fixture.detectChanges(). 那个运行钩子。


推荐阅读