Тест ответа на обещание службы Angular с использованием jasmine
Я создал проект, и он содержит службу, которая возвращает логический ответ обещания. Итак, я написал спецкод, чтобы проверить код и его падение. Ошибка, как показано ниже,
Ожидал, что «да» будет «нет».
пожалуйста, помогите мне определить проблему, которую я сделал при тестировании ответа на обещание?.
Пример кода, как показано ниже.
Услуга
@Injectable({
providedIn: "root"
})
export class CustomerService {
constructor() {}
isValid() : Promise<boolean> {
return Promise.resolve(true);
}
}
Компонент
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.scss']
})
export class CustomerComponent implements OnInit {
icon = new BehaviorSubject('yes');
constructor(private readonly customerService : CustomerService) {
}
ngOnInit(): void {
this.customerService.isValid().then(isValid => {
if(isValid){
this.icon.next('yes');
} else{
this.icon.next('no');
}
});
}
}
Тестовый компонент
describe('CustomerComponent', () => {
let component: CustomerComponent;
let fixture: ComponentFixture<CustomerComponent>;
let customerServiceSpy: jasmine.SpyObj<CustomerService>;
beforeEach(async () => {
customerServiceSpy = jasmine.createSpyObj<CustomerService>(['isValid']);
await TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
declarations: [
CustomerComponent,
],
providers: [
{ provide: CustomerService, useValue: customerServiceSpy },
]
}).compileComponents();
fixture = TestBed.createComponent(CustomerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
fit('should change initial value of icon according to the response of isValid function', waitForAsync(() => {
fixture.detectChanges();
customerServiceSpy.isValid.and.returnValue(Promise.resolve(false));
component.ngOnInit();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.icon.value).toBe('no');
});
customerServiceSpy.isValid.and.returnValue(Promise.resolve(true));
component.ngOnInit();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.icon.value).toBe('yes');
});
}));
});
1 ответ
Положите два ожидания в их собственное испытание. Ожидание находится внутри обещания, поэтому второй шпион запускается до запуска кода внутри обещания. Или вместо того, чтобы положить ваше ожидание в обещание, перезвоните, сделайтеawait fixture.whenStable();
поэтому весь код after запускается после того, как обещание разрешено.