I have managed to set up automatic unit (component) testing in an Angular 8 application using Karma and Jasmine. It properly runs all the test and also displays the component content in a decent way (can see how the data actually change the component).
However, I am want to be able to slow down the test run from time to time to see how the component looks after each test. Of course, this is not required for the pipeline, but would be nice for some debugging sessions + demo purposes.
I have tried using afterEach
function to perform a long tick
, but the function ends much faster than expected.
const testBedConfiguration = {
imports: [
ComponentTestingModule,
CustomCoreModule
],
declarations: [TableLevelTagListComponent],
providers: [
// mocked services
{ provide: LoggingService, useClass: MockedLoggingService },
{ provide: SecurityTagCustomService, useClass: MockedSecurityTagCustomService },
{ provide: SecurityTagsService, useClass: MockedSecurityTagsService}
]
};
describe("TableLevelTagListComponent", () => {
let component: TableLevelTagListComponent;
let fixture: ComponentFixture<TableLevelTagListComponent>;
const getDebugElement = () => fixture.debugElement;
const btnLoadFromApi = () => getDebugElement().query(e => e.nativeElement.id === "btnLoadFromApi").nativeElement;
beforeEach(async(() => {
TestBed.configureTestingModule(testBedConfiguration)
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TableLevelTagListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(fakeAsync(() => {
console.log("Trying to wait after the test");
tick(1000);
}));
it("TableLevelTagListComponent should be created", () => {
expect(component).toBeTruthy();
});
it("positive testing of getting information from own API",
fakeAsync(inject( [SecurityTagCustomService], (tagService: MockedSecurityTagCustomService) => {
setupSimpleMockService(tagService, fixture, () => {
console.log("Btn load from api", btnLoadFromApi());
btnLoadFromApi().click();
});
component.tagList$.subscribe(tags => {
console.log("Received some tags from own API: ", tags);
fixture.detectChanges();
expect(tags.length).toBeGreaterThan(3);
expect(tags[0].id).toEqual("TableTag1");
});
})));
I am using ngrx/Store and all my tests are async (fakeAsync
).
Question: How to wait when testing asynchronous code in Angular 8 with Jasmine?
As I mentioned in the comments, a quick and relatively straightforward solution to your problem is to simply use async()
and setTimeout()
to achieve actual wait times in Angular 8 using Jasmine.
You showed it in an afterEach()
, or it could replace the logic in the it()
spec as well, but modifying the clause you have in the answer directly would look just as you showed, copied here simply for clarity as the comment above doesn't allow for proper spacing:
afterEach(async(() => {
console.log("Trying to wait after the test");
setTimeout(() => { }, 1000);
}));