因此,我试图根据 observable 是否发出某些值来测试 HTML。我有服务的初始设置以使 observable 发出正确的值,但是当我去创建另一个测试以测试如果我传递错误数据会发生什么时,我无法更改 observable 发出的值。我觉得我错过了一些小东西,有人可以看看,让我知道我做错了什么吗?
这是规格文件
describe('AlertsComponent', () => {
let component: AlertsComponent;
let fixture: ComponentFixture<AlertsComponent>;
let alertService: any;
let testAlertGood: Alert = {
type: AlertType.Success,
title: 'Test title',
message: 'Test message',
forceAction: false
};
let testAlertBad: String = 'bad alert';
let testAlertNoTitle: Alert = {
type: AlertType.Success,
title: null,
message: 'Test message',
forceAction: false
};
beforeEach(async(() => {
alertService = jasmine.createSpy('AlertService');
alertService.alert$ = cold('a', { a: testAlertGood });
TestBed.configureTestingModule({
declarations: [ AlertsComponent ],
schemas: [ NO_ERRORS_SCHEMA ],
providers: [
{
provide: Router,
useClass: class { navigate = jasmine.createSpy('navigate'); }
},
{
provide: AlertService,
useValue: alertService
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AlertsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should create', () => {
expect(component).toBeTruthy();
});
it('should display an alert if the alert$ observable has an Alert value', async () => {
fixture.detectChanges();
getTestScheduler().flush();
fixture.detectChanges();
const alertElements = fixture.debugElement.queryAll(By.css('.alert-container'));
const alertIconContainer = fixture.debugElement.query(By.css('.icon-container'));
const alertIconClass = fixture.debugElement.query(By.css('#alert-icon'));
const alertTitle = fixture.debugElement.query(By.css('.title'));
const alertBody = fixture.debugElement.query(By.css('.body'));
expect(alertElements.length).toBe(1);
expect(alertIconContainer.nativeElement.getAttribute('class')).toContain('bg-success');
expect(alertIconClass.nativeElement.getAttribute('class')).toContain('fa-check-circle');
expect(alertTitle.nativeElement.innerText).toContain('Test title');
expect(alertBody.nativeElement.innerText).toContain('Test message');
});
it('should hide the title p tag if the Alert.title is null', async () => {
alertService.alert$ = cold('a', { a: testAlertNoTitle });
fixture.detectChanges();
getTestScheduler().flush();
fixture.detectChanges();
const alertTitle = fixture.debugElement.query(By.css('.title'));
expect(alertTitle).toBeNull();
});
});
所以基本上在文件的顶部,我有三个版本的值,当可观察对象发出时我需要测试它们,我只能测试第一个。should display an alert if the alert$
测试通过就好了,但它是最后一个失败的测试should hide the title...
,因为当我这样做时它似乎并没有改变可观察的alertService.alert$ = cold('a', { a: testAlertNoTitle });