Skip to content

Instantly share code, notes, and snippets.

@Kamilnaja
Last active November 18, 2023 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kamilnaja/cbffe5ab75c1cf14d6928651c6d35a2b to your computer and use it in GitHub Desktop.
Save Kamilnaja/cbffe5ab75c1cf14d6928651c6d35a2b to your computer and use it in GitHub Desktop.
Angular testing
import { HttpClientTestingModule } from '@angular/common/http/testing';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
} from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MockPipe, MockProvider } from 'ng-mocks';
import { BehaviorSubject, take } from 'rxjs';
import { FoodsComponent } from './foods.component';
import { Tag } from './tags.model';
import { TagsState } from './tags.state';
import { UppercaseEverySecondPipe } from './uppercase-every-second.pipe';
describe('FoodsComponent', () => {
let component: FoodsComponent;
let fixture: ComponentFixture<FoodsComponent>;
const tags$ = new BehaviorSubject<Tag[]>([]);
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FoodsComponent, MockPipe(UppercaseEverySecondPipe)],
imports: [HttpClientTestingModule, ReactiveFormsModule],
providers: [
MockProvider(TagsState, {
tags$,
}),
],
}).compileComponents();
fixture = TestBed.createComponent(FoodsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should have tags', fakeAsync(() => {
const tag = {
id: '1',
name: 'tag1',
};
tags$.next([tag]);
component.tags$.pipe(take(1)).subscribe((tags) => {
expect(tags.length).toBe(1);
expect(tags).toEqual([tag]);
});
flush();
}));
it('should have 3 tags', fakeAsync(() => {
const tag1 = {
id: '1',
name: 'tag1',
};
const tag2 = {
id: '2',
name: 'tag2',
};
const tag3 = {
id: '3',
name: 'tag3',
};
tags$.next([tag1, tag2, tag3]);
component.tags$.pipe(take(1)).subscribe((tags) => {
expect(tags.length).toBe(3);
expect(tags).toEqual([tag1, tag2, tag3]);
});
flush();
}));
it('should have no tags', fakeAsync(() => {
tags$.next([]);
component.tags$.pipe(take(1)).subscribe((tags) => {
expect(tags.length).toBe(0);
expect(tags).toEqual([]);
});
flush();
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment