Reputation: 393
I would like to test my function which has a callback at the end like this :
const authorizer = (event, context, callback) => {
const token = event.authorizationToken;
try {
{...}
callback(null, policyDocument)
} catch (e) {
callback('Unauthorized');
}
};
But when i try to test it with jest, it return "callback is not a function". So i would like to know how to mock the callback at the end and how to call it in my jest file.
PS : my authorizer test part looks like this :
describe('authorizer', () => {
let mockCallback, var1, var2, var3, event;
beforeEach(async() => {
mockCallback = jest.fn().mockReturnValue('ok')
var 1 ='...'
var 2 ='...'
var 3 ='...'
event = '...'
actualValue = await authorize.authorizer(event, null, mockCallback)
})
it('should authorize', async () => {
expect(actualValue).toHaveBeenCalled()
})
})
response :
Matcher error: received value must be a mock or spy function
Received has value: undefined
Upvotes: 0
Views: 1196
Reputation: 102207
Here is the solution:
index.ts
:
export const authorizer = (event, context, callback) => {
const token = event.authorizationToken;
const policyDocument = {};
try {
callback(null, policyDocument);
} catch (e) {
callback('Unauthorized');
}
};
index.spec.ts
:
import { authorizer } from './';
describe('authorizer', () => {
it('should authorize', () => {
const event = 'message';
const mockCallback = jest.fn().mockReturnValue('ok');
authorizer(event, null, mockCallback);
expect(mockCallback).toHaveBeenCalled();
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59371450/index.spec.ts (10.989s)
authorizer
✓ should authorize (5ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 83.33 | 100 | 100 | 83.33 | |
index.ts | 83.33 | 100 | 100 | 83.33 | 7 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.907s
Upvotes: 1