Testing NodeJs applications and serverless functions:
A previous post described running the application locally as a way of testing the code without
requiring it to be deployed anywhere remote from the development server. This
write-up follows up on it with a test case.
One way to write unit-tests and integration tests is to use
Jest. It’s testing framework with a name that goes with its approach to be
delightfully simple. It works on all forms of JavaScript and TypeScript such as
Node, React, Angular and others.
A sample Jest unit script might look like this:
__tests__\unit\handlers\simple.test.js:
// Mock uuid
const uuidvalue
= 'f8216640-91a2-11eb-8ab9-57aa454facef'
jest.mock('uuid',
() => ({ v1: () => uuidvalue}));
// This
includes all tests for documents handler
describe('Test simple
handler', () => {
let sendSpy;
// Test one-time setup and teardown, see
more in https://jestjs.io/docs/en/setup-teardown
beforeAll(() => {
// Mock s3 methods
// https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname
sendSpy = jest.spyOn(Array.prototype,
'push');
});
// Clean up mocks
afterAll(() => {
sendSpy.mockRestore();
});
it('should simply return', async () =>
{
const items = {
"Items": [
],
"Count": 0,
"ScannedCount": 0
};
// Return the specified value whenever
the spied function is called
sendSpy.mockReturnValue(items);
const event = {
"httpMethod":
"GET",
"rawPath":
"/documents",
"requestContext": {
"requestId":"e0GDshQXoAMEJug="
}
}
// Invoke Lambda handler
var foo = new Array("foo",
"bar");
const result = foo.push("echo");
const expectedResult = {
statusCode: 200,
body: JSON.stringify(items),
headers : {
"Content-Type":
"application/json"
}
};
// Compare the result with the expected
result
expect(result).toEqual(expectedResult);
});
});
node_modules\.bin\jest
PASS
./__tests__/unit/handlers/simple.test.js
Test simple handler
√ should simply
return (1 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed,
1 total
Snapshots: 0 total
Time: 0.279 s,
estimated 1 s
Ran all test suites.
No comments:
Post a Comment