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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,6 @@ testem.log
Thumbs.db

src/environments/environment.ts
src/environments/environment.ci.ts
src/environments/environment.ci.ts
/tsconfig.spec.agent-*.json
/coverage
12 changes: 11 additions & 1 deletion angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,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/mmu-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",
"commit": "cz",
"lint:fix": "ng lint --fix",
Expand Down
183 changes: 183 additions & 0 deletions src/app/app-modules/captcha-service/captcha.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* 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 { TestBed } from '@angular/core/testing';
import { CaptchaService } from './captcha.service';
import { environment } from 'src/environments/environment';

describe('CaptchaService', () => {
let service: CaptchaService;
let originalAppendChild: <T extends Node>(node: T) => T;

beforeEach(() => {
TestBed.configureTestingModule({
providers: [CaptchaService],
});
service = TestBed.inject(CaptchaService);
originalAppendChild = document.head.appendChild.bind(document.head);
});

afterEach(() => {
// Clean up any script elements added during tests
const scripts = document.head.querySelectorAll('script');
scripts.forEach(script => {
if (
script.src &&
script.src.includes(environment.captchaChallengeURL || 'captcha')
) {
script.remove();
}
});
});

it('should be created', () => {
expect(service).toBeTruthy();
});

describe('#loadScript', () => {
it('should return a Promise', async () => {
let added: any;
spyOn(document.head, 'appendChild').and.callFake((node: any) => {
added = node;
return node;
});
const result = service.loadScript();
expect(result).toBeInstanceOf(Promise);
added.onerror(new Event('error'));
await expectAsync(result).toBeRejected();
});

it('should append a script element to document.head', async () => {
const appendChildSpy = spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
(node as any).onload(new Event('load'));
return node;
}
);

await service.loadScript();
expect(appendChildSpy).toHaveBeenCalled();
});

it('should set script src to environment.captchaChallengeURL', async () => {
let capturedScript: HTMLScriptElement | null = null;
spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
capturedScript = node as any;
(capturedScript as any).onload(new Event('load'));
return node;
}
);

await service.loadScript();
expect(capturedScript!.src).toContain(environment.captchaChallengeURL);

Check warning on line 92 in src/app/app-modules/captcha-service/captcha.service.spec.ts

View workflow job for this annotation

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

Forbidden non-null assertion
});

it('should set async and defer on the script element', async () => {
let capturedScript: HTMLScriptElement | null = null;
spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
capturedScript = node as any;
(capturedScript as any).onload(new Event('load'));
return node;
}
);

await service.loadScript();
expect(capturedScript!.async).toBe(true);

Check warning on line 106 in src/app/app-modules/captcha-service/captcha.service.spec.ts

View workflow job for this annotation

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

Forbidden non-null assertion
expect(capturedScript!.defer).toBe(true);

Check warning on line 107 in src/app/app-modules/captcha-service/captcha.service.spec.ts

View workflow job for this annotation

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

Forbidden non-null assertion
});

it('should resolve when script loads successfully', async () => {
spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
(node as any).onload(new Event('load'));
return node;
}
);

await expectAsync(service.loadScript()).toBeResolved();
});

it('should set scriptLoaded to true after successful load', async () => {
spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
(node as any).onload(new Event('load'));
return node;
}
);

await service.loadScript();
// Verify by calling again - it should resolve immediately without appending
const appendChildSpy = document.head.appendChild as jasmine.Spy;
appendChildSpy.calls.reset();

await service.loadScript();
expect(appendChildSpy).not.toHaveBeenCalled();
});

it('should resolve immediately if script is already loaded', async () => {
spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
(node as any).onload(new Event('load'));
return node;
}
);

await service.loadScript();
const appendChildSpy = document.head.appendChild as jasmine.Spy;
appendChildSpy.calls.reset();

await service.loadScript();
expect(appendChildSpy).not.toHaveBeenCalled();
});

it('should reject with Error when script fails to load', async () => {
spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
(node as any).onerror(new Event('error'));
return node;
}
);

await expectAsync(service.loadScript()).toBeRejectedWithError(
/Failed to load CAPTCHA script/
);
});

it('should include the captchaChallengeURL in the error message', async () => {
spyOn(document.head, 'appendChild').and.callFake(
<T extends Node>(node: T): T => {
(node as any).onerror(new Event('error'));
return node;
}
);

try {
await service.loadScript();
fail('Expected an error to be thrown');
} catch (e: any) {
expect(e.message).toContain(environment.captchaChallengeURL);
}
});
});
});
121 changes: 121 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,121 @@
/*
* 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 { CaptchaComponent } from './captcha.component';
import { CaptchaService } from '../captcha-service/captcha.service';
import { environment } from 'src/environments/environment';
import { NO_ERRORS_SCHEMA } from 'src/testing/test-utils';

describe('CaptchaComponent', () => {
let component: CaptchaComponent;
let fixture: ComponentFixture<CaptchaComponent>;
let captchaService: { loadScript: jasmine.Spy };
let turnstileMock: any;
let hadTurnstile: boolean;
let previousTurnstile: any;

beforeEach(async () => {
hadTurnstile = 'turnstile' in window;
previousTurnstile = (window as any).turnstile;
turnstileMock = {
render: jasmine.createSpy('render').and.returnValue('widget-1'),
reset: jasmine.createSpy('reset'),
remove: jasmine.createSpy('remove'),
};
(window as any).turnstile = turnstileMock;
captchaService = {
loadScript: jasmine.createSpy('loadScript').and.resolveTo(undefined),
};

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 = previousTurnstile;
else delete (window as any).turnstile;
});

it('loads the script and renders the widget into the container', async () => {
fixture.detectChanges();
await fixture.whenStable();
await component.ngAfterViewInit();
expect(captchaService.loadScript).toHaveBeenCalled();
expect(turnstileMock.render).toHaveBeenCalledTimes(1);
const [el, opts] = turnstileMock.render.calls.mostRecent().args;
expect(el.id).toBe('cf-turnstile');
expect(opts.sitekey).toBe(environment.siteKey);
expect(opts.theme).toBe('light');
});

it('emits the token from the widget callback', async () => {
fixture.detectChanges();
await fixture.whenStable();
const emitted: string[] = [];
component.tokenResolved.subscribe(t => emitted.push(t));
turnstileMock.render.calls.mostRecent().args[1].callback('tok-123');
expect(emitted).toEqual(['tok-123']);
});

it('does not render when the container is missing', async () => {
component.captchaRef = undefined as any;
await component.ngAfterViewInit();
expect(turnstileMock.render).not.toHaveBeenCalled();
});

it('swallows script loading errors', async () => {
captchaService.loadScript.and.rejectWith(new Error('fail'));
fixture.detectChanges();
await expectAsync(component.ngAfterViewInit()).toBeResolved();
expect(turnstileMock.render).not.toHaveBeenCalled();
});

it('reset() and ngOnDestroy() act on the rendered widget', async () => {
fixture.detectChanges();
await fixture.whenStable();
component.reset();
expect(turnstileMock.reset).toHaveBeenCalledWith('widget-1');
component.ngOnDestroy();
expect(turnstileMock.remove).toHaveBeenCalledWith('widget-1');
});

it('reset() and ngOnDestroy() do nothing before a widget exists', () => {
component.reset();
component.ngOnDestroy();
expect(turnstileMock.reset).not.toHaveBeenCalled();
expect(turnstileMock.remove).not.toHaveBeenCalled();
});

it('ngOnDestroy() skips removal when turnstile has no remove()', async () => {
fixture.detectChanges();
await fixture.whenStable();
delete turnstileMock.remove;
expect(() => component.ngOnDestroy()).not.toThrow();
});
});
Loading
Loading