我不明白为什么我的单元测试会失败。我如何检查我的异步条件在存储调度后是否已经满足?我想检查3件事:
1/我的组件在分派后是真实的(条件设置为真后)
2/当模式为AddMode('La note a été ajoutée)时,内部文本正确
3/当模式不是AddMode('la note a été modifiée')时,内部文本正确
我正在使用"fakeAsync"测试异步行为,但它没有按预期工作。
我错过了什么?
谢谢大家。
HTML代码:
<ng-container *ngIf="(isToastVisible$ | async)">
<div *ngIf="(isAddMode| async)"
class="position-fixed bottom-0 start-50 translate-middle-x p-3 border border-success bg-success text-white"
style="z-index: 11">La note a été ajoutée !</div>
<div *ngIf="!(isAddMode | async)"
class="position-fixed bottom-0 start-50 translate-middle-x p-3 border border-success bg-success text-white"
style="z-index: 11">La note a été modifiée !</div>
</ng-container>
类型脚本:
import { Component, OnInit } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { showAddEditNoteToast, AddEditNoteModalMode } from 'src/app/reducers/selectors/selectors';
@Component({
selector: 'app-toast',
templateUrl: './toast.component.html',
styleUrls: ['./toast.component.scss']
})
export class ToastComponent implements OnInit {
public isToastVisible$: Observable<boolean>;
public isAddMode$: Observable<boolean>;
constructor(
private store: Store
) { }
ngOnInit(): void {
this.isToastVisible$ = this.store.pipe(select(showAddEditNoteToast));
this.isAddMode$ = this.store.pipe(select(AddEditNoteModalMode));
}
}
SPEC.TS:
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { ToastComponent } from './toast.component';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { Initialstate } from '../../app/reducers/index';
import { setFormMode, showAddEditNoteModal } from 'src/app/reducers/actions/actions';
import { By } from '@angular/platform-browser';
describe('ToastComponent', () => {
let component: ToastComponent;
let fixture: ComponentFixture<ToastComponent>;
let store: MockStore;
const initialState = Initialstate;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ToastComponent],
providers: [
provideMockStore({ initialState })
]
})
.compileComponents();
store = TestBed.inject(MockStore)
});
beforeEach(() => {
fixture = TestBed.createComponent(ToastComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create Toast component ', fakeAsync(() => {
store.dispatch(showAddEditNoteModal({ showAddEditNoteModal: true }));
tick();
expect(component).toBeTruthy();
}));
it('should render text - La note a été ajoutée !', fakeAsync(() => {
store.dispatch(setFormMode({ isAddMode: true }));
fixture.detectChanges();
tick();
const text = fixture.debugElement.nativeElement;
expect(text).toEqual('La note a été ajoutée !')
}))
});
1条答案
按热度按时间zpgglvta1#
即使没有操作分派或
tick
,您的第一个测试也应该通过,因为它只是检查组件示例是否已创建,而不是检查操作执行的任何特定操作。在第二个示例中,需要检查
div
元素的文本内容:const text = fixture.debugElement.query(By.css('div')).nativeElement.innerText;
您可能还需要在
text
上使用trim()
。