Skip to content

Commit

Permalink
Update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
peterMuriuki committed Nov 5, 2024
1 parent 40387f6 commit 40db7d5
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 36 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ jobs:
- name: Lint
run: yarn lint

- name: Run all tests
run: yarn test
- name: Run core tests
run: yarn turbo run test --filter @onaio/symbology-calc-core

- uses: actions/upload-artifact@v4
if: always()
Expand Down
20 changes: 11 additions & 9 deletions packages/core/src/evaluator/tests/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { OnaApiService } from '../../services/onaApi/services';
import * as services from '../../services/onaApi/services';
import { createConfigs, form3623Submissions } from './fixtures/fixtures';
import { transformFacility, createMetricFactory } from '../helpers/utils';
import { colorDeciderFactory } from '../../helpers/utils';
Expand All @@ -9,6 +9,8 @@ import {
} from '../../constants';
import { RegFormSubmission } from '../../helpers/types';

const {OnaApiService} = services

// eslint-disable-next-line @typescript-eslint/no-var-requires
const nock = require('nock');

Expand Down Expand Up @@ -132,7 +134,7 @@ describe('transform facility tests', () => {
query: `{"facility": ${regFomSubmission._id}}`, // filter visit submissions for this facility
sort: `{"${dateOfVisitAccessor}": -1}`
})
.reply(502, { message: 'error' });
.reply(400, { message: 'error' }).persist();

// after attempt
nock(baseUrl)
Expand All @@ -143,14 +145,14 @@ describe('transform facility tests', () => {
query: `{"facility": ${regFomSubmission._id}}`, // filter visit submissions for this facility
sort: `{"${dateOfVisitAccessor}": -1}`
})
.reply(400, { message: 'error' });
.reply(400, { message: 'error' }).persist();

nock(baseUrl)
.post(`/${editSubmissionEndpoint}`, {
id: '3623',
submission: {
...regFomSubmission,
'marker-color': 'green',
'marker-color': 'red',
meta: {
instanceID: 'uuid:0af4f147-d5fd-486a-bf76-d1bf850cc976',
deprecatedID: regFomSubmission['meta/instanceID']
Expand All @@ -172,18 +174,18 @@ describe('transform facility tests', () => {
logger
);

expect(response).toEqual({
expect(response).toMatchObject({
_value: undefined,
detail: {
code: 'ECODE3',
recsAffected: 0
},
error: '400: {"message":"error"}: Network request failed.',
error: expect.any(String),
isFailure: true,
isSuccess: false
});
expect(response.error).toEqual('400: {"message":"error"}: Network request failed.');
});
expect(response.error).toContain("Request failed for | URL: http://sample.com/api/v1/data/3624?page_size=1&page=1&query=%7B%22facility%22%3A+304870%7D&sort=%7B%22endtime%22%3A+-1%7D | Status: 400");
}, 20000);

it('cancelling request works', async () => {
const apiToken = 'apiToken';
Expand Down Expand Up @@ -241,7 +243,7 @@ describe('transform facility tests', () => {
code: 'ECODE3',
recsAffected: 0
},
error: 'AbortError: The user aborted a request..',
"error": "Error Name: AbortError | Message: The user aborted a request.",
isFailure: true,
isSuccess: false
});
Expand Down
9 changes: 4 additions & 5 deletions packages/core/src/evaluator/tests/pipelinesController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,10 @@ it('error when fetching the registration form', async () => {
expect(loggerMock.mock.calls).toEqual([
[
{
level: 'error',
message:
'Operation to fetch form: 3623, failed with err: Error: 400: Could not find form with id: Network request failed.'
}
]
"level": "error",
"message": "Operation to fetch form: 3623, failed with err: Request failed for | URL: https://test-api.ona.io/api/v1/forms/3623 | Status: 400",
},
],
]);

expect(nock.pendingMocks()).toEqual([]);
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/helpers/Result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ export class Result<T> {

function getErrorDescription(error: Error){
const { name, message, cause } = error;
const code = (cause as Record<string, unknown>).code as string | undefined
const causeMessage = (cause as Record<string, unknown>).message as string | undefined
const code = (cause as Record<string, unknown> | undefined)?.code as string | undefined
const causeMessage = (cause as Record<string, unknown> | undefined)?.message as string | undefined
const errorDetails = [];

if (name) errorDetails.push(`Error Name: ${name}`);
Expand Down
52 changes: 34 additions & 18 deletions packages/core/src/services/onaApi/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const customFetch = async (input: RequestInfo, init?: RequestInit, logger
: `Retrying request ${input}; Attempt ${attempt}; Request does not have a response`;
logger?.(createVerboseLog(msg));
}
if(attempt >= numOfRetries){
if (attempt >= numOfRetries) {
retry = false
}
return retry;
Expand All @@ -55,7 +55,11 @@ export const customFetch = async (input: RequestInfo, init?: RequestInit, logger
}
};

return persistentFetch(input, requestOptionsWithRetry)
const response = await persistentFetch(input, requestOptionsWithRetry)
if (response && !response.ok) {
throw throwHttpError(response)
}
return await response.json()
};

/** Service class that abstracts function calls to ona data api */
Expand Down Expand Up @@ -95,9 +99,7 @@ export class OnaApiService {
return customFetch(formUrl, { ...this.getCommonFetchOptions() }, this.logger)
.then((res) => {
this.logger?.(createVerboseLog(`Fetched form wih form id: ${formId}`));
return res.json().then((form: Form) => {
return Result.ok<Form>(form);
});
return Result.ok<Form>(res);
})
.catch((err: Error) => {
this.logger?.(
Expand Down Expand Up @@ -173,14 +175,12 @@ export class OnaApiService {
this.logger
)
.then((res) => {
return (res.json() as Promise<FormSubmissionT[]>).then((res) => {
this.logger?.(
createInfoLog(
`Fetched ${res.length} submissions for form id: ${formId} page: ${paginatedSubmissionsUrl}`
)
);
return Result.ok(res);
});
this.logger?.(
createInfoLog(
`Fetched ${res.length} submissions for form id: ${formId} page: ${paginatedSubmissionsUrl}`
)
);
return Result.ok(res);
})
.catch((err: Error) => {
this.logger?.(
Expand All @@ -189,10 +189,10 @@ export class OnaApiService {
)
);
let recsAffected = pageSize;
if((totalSubmissions - (page * pageSize)) < pageSize )[
if ((totalSubmissions - (page * pageSize)) < pageSize) [
recsAffected = totalSubmissions - (page * pageSize)
]
return Result.fail<FormSubmissionT[]>(err, {code: NETWORK_ERROR, recsAffected, });
return Result.fail<FormSubmissionT[]>(err, { code: NETWORK_ERROR, recsAffected, });
});
} while (page * pageSize <= totalSubmissions);
}
Expand Down Expand Up @@ -236,9 +236,7 @@ export class OnaApiService {
`Edited submission with _id: ${submissionPayload._id} for form: ${formId}`
)
);
return res.json().then((response) => {
return Result.ok<Record<string, string>>(response);
});
return Result.ok<Record<string, string>>(res);
})
.catch((err) => {
this.logger?.(
Expand Down Expand Up @@ -269,3 +267,21 @@ export async function upLoadMarkerColor(
};
return service.editSubmission(formId, newSubmission);
}


function throwHttpError(response: Response) {
const { status, url } = response;
let errorDetails = [];

if (url) errorDetails.push(`URL: ${url}`);
if (status) errorDetails.push(`Status: ${status}`);
if(errorDetails.length){
errorDetails = ["Request failed for", ...errorDetails]
}

const errorMessage = errorDetails.length > 0
? errorDetails.join(' | ')
: "An unknown network error occurred.";

return errorMessage
}

0 comments on commit 40db7d5

Please sign in to comment.