Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,7 @@ testem.log
Thumbs.db

/src/environments/environment.ts
/src/environments/environment.ci.ts
/src/environments/environment.ci.ts
/tsconfig.spec.agent-*.json
/coverage
/.angular
12 changes: 11 additions & 1 deletion angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,17 @@
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.css"
],
"scripts": []
"scripts": [],
"karmaConfig": "karma.conf.js",
"codeCoverageExclude": [
"Common-UI/**",
"src/testing/**",
"src/environments/**",
"src/test.ts",
"src/polyfills.ts",
"src/main.ts",
"**/mocks/**"
]
}
},
"lint": {
Expand Down
50 changes: 50 additions & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma'),
],
client: {
jasmine: {
random: false,
timeoutInterval: 10000,
},
captureConsole: false,
},
jasmineHtmlReporter: {
suppressAll: true,
},
coverageReporter: {
dir: process.env.COVERAGE_DIR || require('path').join(__dirname, './coverage/tm-ui'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'lcovonly' },
{ type: 'json-summary' },
{ type: 'text-summary' },
],
},
reporters: ['progress', 'kjhtml'],
browsers: ['ChromeHeadlessCI'],
customLaunchers: {
ChromeHeadlessCI: {
base: 'ChromeHeadless',
flags: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'],
},
},
browserNoActivityTimeout: 300000,
browserDisconnectTimeout: 60000,
browserDisconnectTolerance: 2,
captureTimeout: 300000,
singleRun: true,
restartOnFileChange: false,
});
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"test:ci": "(test -f src/environments/environment.ts || cp src/environments/environment.test.ts src/environments/environment.ts) && ng test --watch=false --code-coverage",
"lint": "ng lint",
"lint:fix": "ng lint --fix",
"prepare": "husky install",
Expand Down
123 changes: 123 additions & 0 deletions src/app/app-modules/captcha/captcha.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* AMRIT – Accessible Medical Records via Integrated Technology
* Integrated EHR (Electronic Health Records) Solution
*
* Copyright (C) "Piramal Swasthya Management and Research Institute"
*
* This file is part of AMRIT.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from 'src/testing/test-utils';
import { environment } from 'src/environments/environment';
import { CaptchaService } from '../core/services/captcha.service';
import { CaptchaComponent } from './captcha.component';

describe('CaptchaComponent', () => {
let component: CaptchaComponent;
let fixture: ComponentFixture<CaptchaComponent>;
let captchaService: any;
let turnstile: any;
let hadTurnstile: boolean;
let prevTurnstile: any;

beforeEach(async () => {
hadTurnstile = 'turnstile' in window;
prevTurnstile = (window as any).turnstile;
turnstile = {
render: jasmine.createSpy('render').and.returnValue('widget-1'),
reset: jasmine.createSpy('reset'),
remove: jasmine.createSpy('remove'),
};
(window as any).turnstile = turnstile;
captchaService = {
loadScript: jasmine
.createSpy('loadScript')
.and.returnValue(Promise.resolve()),
};
await TestBed.configureTestingModule({
declarations: [CaptchaComponent],
providers: [{ provide: CaptchaService, useValue: captchaService }],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
fixture = TestBed.createComponent(CaptchaComponent);
component = fixture.componentInstance;
});

afterEach(() => {
if (hadTurnstile) (window as any).turnstile = prevTurnstile;
else delete (window as any).turnstile;
});

it('renders the turnstile widget after the script loads and emits tokens', async () => {
const tokens: string[] = [];
component.tokenResolved.subscribe((t) => tokens.push(t));
fixture.detectChanges();
await fixture.whenStable();
await component.ngAfterViewInit();
expect(captchaService.loadScript).toHaveBeenCalled();
// rendered only once even though ngAfterViewInit ran twice
expect(turnstile.render).toHaveBeenCalledTimes(1);
const [el, opts] = turnstile.render.calls.mostRecent().args;
expect(el).toBe(component.captchaRef.nativeElement);
expect(opts.sitekey).toBe(environment.siteKey);
expect(opts.theme).toBe('light');
opts.callback('tok-123');
expect(tokens).toEqual(['tok-123']);
});

it('logs and stops when the container element is missing', async () => {
const err = spyOn(console, 'error');
component.captchaRef = undefined as any;
await component.ngAfterViewInit();
expect(err).toHaveBeenCalledWith('CAPTCHA container element not found');
expect(turnstile.render).not.toHaveBeenCalled();
});

it('logs when the script fails to load', async () => {
const err = spyOn(console, 'error');
const failure = new Error('nope');
captchaService.loadScript.and.returnValue(Promise.reject(failure));
await component.ngAfterViewInit();
expect(err).toHaveBeenCalledWith('Failed to initialize CAPTCHA:', failure);
});

it('reset and destroy use the widget id', async () => {
component.captchaRef = { nativeElement: document.createElement('div') };
await component.ngAfterViewInit();
component.reset();
expect(turnstile.reset).toHaveBeenCalledWith('widget-1');
component.ngOnDestroy();
expect(turnstile.remove).toHaveBeenCalledWith('widget-1');
});

it('reset and destroy are no-ops without a widget', () => {
component.reset();
component.ngOnDestroy();
expect(turnstile.reset).not.toHaveBeenCalled();
expect(turnstile.remove).not.toHaveBeenCalled();
});

it('reset and destroy are no-ops when turnstile is unavailable', async () => {
component.captchaRef = { nativeElement: document.createElement('div') };
await component.ngAfterViewInit();
delete (window as any).turnstile;
component.reset();
component.ngOnDestroy();
expect(turnstile.reset).not.toHaveBeenCalled();
expect(turnstile.remove).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,77 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialogRef } from '@angular/material/dialog';
import { of } from 'rxjs';
import { AllergenSearchComponent } from './allergen-search.component';
import { MasterdataService } from 'src/app/app-modules/nurse-doctor/shared/services';
import {
COMMON_TEST_IMPORTS,
LANGUAGE_EN,
NO_ERRORS_SCHEMA,
autoSpy,
commonTestProviders,
throwingObs,
} from 'src/testing/test-utils';

describe('AllergenSearchComponent', () => {
let fixture: ComponentFixture<AllergenSearchComponent>;
let component: AllergenSearchComponent;
let master: any;
let dialogRef: any;
const results = () => [
{ conceptID: 'A1', term: 'Peanut' },
{ conceptID: 'A2', term: 'Dust' },
];

beforeEach(async () => {
master = autoSpy(MasterdataService);
master.searchDiagnosisBasedOnPageNo1.and.callFake(() =>
of({ statusCode: 200, data: { sctMaster: results(), pageCount: 3 } }),
);
await TestBed.configureTestingModule({
imports: [...COMMON_TEST_IMPORTS],
declarations: [AllergenSearchComponent],
providers: [
...commonTestProviders({ dialogData: { searchTerm: 'pea' } }),
{ provide: MasterdataService, useValue: master },
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
fixture = TestBed.createComponent(AllergenSearchComponent);
component = fixture.componentInstance;
dialogRef = TestBed.inject(MatDialogRef);
});


Check failure on line 65 in src/app/app-modules/core/components/allergen-search/allergen-search.component.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-audit / lint-and-audit

Delete `⏎`
it('ignores short search terms', () => {
component.search('pe', 0);
expect(master.searchDiagnosisBasedOnPageNo1).not.toHaveBeenCalled();
});

Check failure on line 69 in src/app/app-modules/core/components/allergen-search/allergen-search.component.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-audit / lint-and-audit

Delete `⏎`


it('shows no-record message for empty results', () => {
component.assignSelectedLanguage();
master.searchDiagnosisBasedOnPageNo1.and.returnValue(
of({ statusCode: 200, data: { sctMaster: [] } }),
);
component.search('peanut', 0);
expect(component.message).toBe(LANGUAGE_EN.common.noRecordFound);
});

Check failure on line 79 in src/app/app-modules/core/components/allergen-search/allergen-search.component.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-audit / lint-and-audit

Delete `⏎`



Check failure on line 82 in src/app/app-modules/core/components/allergen-search/allergen-search.component.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-audit / lint-and-audit

Delete `⏎`
it('selects a component and submits it', () => {
component.selectComponentName(2, { term: 'Dust' });
expect(component.selectedComponentNo).toBe(2);
expect(component.selectedItem).toEqual({ term: 'Dust' });
component.submitComponentList();
expect(dialogRef.close).toHaveBeenCalledWith({
componentNo: 2,
component: { term: 'Dust' },
});
});

Check failure on line 92 in src/app/app-modules/core/components/allergen-search/allergen-search.component.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-audit / lint-and-audit

Delete `⏎⏎`


});
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,73 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {
ComponentFixture,
TestBed,
discardPeriodicTasks,
fakeAsync,
tick,
} from '@angular/core/testing';
import { of } from 'rxjs';

import { AppFooterComponent } from './app-footer.component';
import { SpecialistLoginComponent } from '../specialist-login/specialist-login.component';
import {
COMMON_TEST_IMPORTS,
LANGUAGE_EN,
NO_ERRORS_SCHEMA,
commonTestProviders,
} from 'src/testing/test-utils';

describe('AppFooterComponent', () => {
let component: AppFooterComponent;
let fixture: ComponentFixture<AppFooterComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [...COMMON_TEST_IMPORTS],
declarations: [AppFooterComponent],
}).compileComponents();
}));
providers: [...commonTestProviders()],
schemas: [NO_ERRORS_SCHEMA],
})
.overrideTemplate(AppFooterComponent, '')
.compileComponents();

beforeEach(() => {
spyOn(console, 'log');
fixture = TestBed.createComponent(AppFooterComponent);
component = fixture.componentInstance;
});

it('sets language and year and polls the online status', fakeAsync(() => {
fixture.detectChanges();
expect(component.currentLanguageSet).toEqual(LANGUAGE_EN);
expect(component.year).toBe(new Date().getFullYear());
expect(component.status).toBeFalse();
tick(1000);
expect(component.status).toBe(navigator.onLine);
discardPeriodicTasks();
}));

it('refreshes language on ngDoCheck', () => {
component.currentLanguageSet = undefined;
component.ngDoCheck();
expect(component.currentLanguageSet).toEqual(LANGUAGE_EN);
});

it('should create', () => {
expect(component).toBeTruthy();
it('openSnackBar opens the specialist login snack bar', () => {
const afterDismissed = jasmine
.createSpy('afterDismissed')
.and.returnValue(of(undefined));
component.snackBar = {
openFromComponent: jasmine
.createSpy('openFromComponent')
.and.returnValue({ afterDismissed }),
};
component.openSnackBar();
expect(component.snackBar.openFromComponent).toHaveBeenCalledWith(
SpecialistLoginComponent,
jasmine.objectContaining({ horizontalPosition: 'right' }),
);
expect(afterDismissed).toHaveBeenCalled();
});
});
Loading
Loading