angular - 角度单元测试道具永远不会未定义
问题描述
我不明白为什么这个简单的测试实际上不起作用。
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');
});
});
解决方案
好吧,TestBed 确实运行了所有必要的生命周期钩子来检测变化。因此,可以预期该变量已定义。不要使用fixture.detectChanges()
. 那个运行钩子。
推荐阅读
- mysql - 有什么方法可以使用 mysql 在 ssh 上对用户进行身份验证?
- facebook - 营销 API - 缺少系统用户权限,使用开发层
- javascript - 如何使用 bootstrap-datetime-picker-for-rails gem 以 UTC 格式而不是本地时间显示日期选择器
- redhat - Red Hat 8 vpn 客户端无法连接到路由器 ac5300 上的 OpenVPN 服务器
- javascript - plotly javascript scatter更新数据
- javascript - 在鼠标悬停期间替换部分 URL 以获得原始大小的图像
- r - 如何使用 R 从共享点文件夹下载文件
- bash - Add multiple commands in single alias
- mysql - 如何创建 API 以在 MySQL 中插入数据,并使用重复键传递 json
- postgresql - PostgreSQL 语法错误我不明白