import { Spec, TestCase } from '@yourcause/test-decorators'; import { DescribeAngularService } from '@yourcause/test-decorators/angular'; import { expect } from 'chai'; import { TokenAdapterService } from './token-adapter.service'; @DescribeAngularService(TokenAdapterService, { }) export class TokenAdapterServiceSpec implements Spec { @TestCase('should be able to offset expiration based on server time') async testShouldOffsetExpiration ( service: TokenAdapterService ) { const now = new Date(); const response = { // set expiration to "now" expiration: now.toISOString(), refreshTokenExpiration: now.toISOString(), token: '', refreshToken: '', requirePasswordReset: false }; // make the "server clock" diff further // in the future to emulate a computer clock that is behind service['diff'] = -(180 * 1000); const newBody = await service.handleTokenRequest(response); // make sure the new expiration is rolled back to match the faked browser clock expect(new Date(newBody.expiration)).to.be.lessThan(now); } @TestCase('should be able to determine diff') async testShouldDetermineDiff (service: TokenAdapterService) { service['diff'] = Infinity; await service['ensureDiffIsSet'](); expect(service['diff']).to.equal(Infinity); service['diff'] = 0; service['isLocalhost'] = false; const serverDate = new Date(Date.now() - 180000).toISOString(); service['getServerTime'] = async () => serverDate; await service['ensureDiffIsSet'](); // need to trim off some milliseconds due to how long tests take to run expect(Math.round(service['diff'] / 1000)).to.equal(180); } @TestCase('should be able to get the date header from XHR') async testShouldGetDateHeader (service: TokenAdapterService) { let loadCb: any; const dateToReturn = new Date().toISOString(); const mockXhr = { open () { }, setRequestHeader () { }, send () { }, getResponseHeader (header: string) { if (header.toLowerCase() === 'date') { return dateToReturn; } return ''; }, addEventListener (e: string, cb: any) { if (e === 'load') { loadCb = cb; } } }; service['getXHR'] = () => (mockXhr as any); const prom = service['getServerTime'](); loadCb(); const result = await prom; expect(result).to.equal(dateToReturn); } }