/** * This file is part of Anis Client. * * @copyright Laboratoire d'Astrophysique de Marseille / CNRS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormSampleComponent } from './form-sample.component'; import { FormsModule, NgForm } from '@angular/forms'; import { ToastrModule } from 'ngx-toastr'; import { Router } from '@angular/router'; import { SearchService } from 'src/app/instance/store/services/search.service'; import { ToastrService } from 'ngx-toastr'; import { Observable, of } from 'rxjs'; class MockRouter { navigate(url: string): string { return url; } } class MockSearch { retrieveDataLength(query: string): Observable<[{ nb: number }]> { return null; } } class MockToastr { error(): void {} } describe('FormSampleComponent', () => { let component: FormSampleComponent; let fixture: ComponentFixture<FormSampleComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [FormSampleComponent], imports: [FormsModule, ToastrModule], providers: [ { provide: Router, useClass: MockRouter }, { provide: ToastrService, useClass: MockToastr }, { provide: SearchService, useClass: MockSearch }, ], }).compileComponents(); fixture = TestBed.createComponent(FormSampleComponent); component = fixture.componentInstance; }); afterEach(() => { jest.resetAllMocks(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should call error if no ids found with the query', () => { const spyOnError = jest.spyOn(MockToastr.prototype, 'error'); const spyOnNavigate = jest.spyOn(MockRouter.prototype, 'navigate'); const spyOnSearch = jest .spyOn(MockSearch.prototype, 'retrieveDataLength') .mockReturnValue(of([{ nb: 0 }])); component.datasetName = 'observations'; component.instanceName = 'default'; let form = { value: { inputVal: 43 } } as NgForm; component.submit(form); expect(spyOnSearch).toHaveBeenCalledTimes(1); expect(spyOnSearch).toHaveBeenCalledWith( 'observations?a=count&c=1::eq::43' ); expect(spyOnError).toHaveBeenCalledTimes(1); expect(spyOnNavigate).toHaveBeenCalledTimes(0); }); it('should call error if no ids found with the query', () => { const spyOnError = jest.spyOn(MockToastr.prototype, 'error'); const spyOnNavigate = jest.spyOn(MockRouter.prototype, 'navigate'); const spyOnSearch = jest .spyOn(MockSearch.prototype, 'retrieveDataLength') .mockReturnValue(of([{ nb: 1 }])); component.datasetName = 'observations'; component.instanceName = 'default'; let form = { value: { inputVal: 250 } } as NgForm; component.submit(form); expect(spyOnSearch).toHaveBeenCalledTimes(1); expect(spyOnSearch).toHaveBeenCalledWith( 'observations?a=count&c=1::eq::250' ); expect(spyOnError).toHaveBeenCalledTimes(0); expect(spyOnNavigate).toHaveBeenCalledTimes(1); expect(spyOnNavigate).toHaveBeenCalledWith( ['/instance/default/search/detail/observations/250'] ); }); });