This is the function I am testing (stripped down for simplicity’s sake): populate.js->
JavaScript
x
12
12
1
const { createSessionID } = require('./populate-template-utilities');
2
3
const createFile = async () => {
4
const responseHeader = {};
5
responseHeader.SessionID = createSessionID();
6
return responseHeader;
7
};
8
9
module.exports = {
10
createFile,
11
};
12
The function this function calls: populate-template-utilities ->
JavaScript
1
9
1
const createSessionID = () => {
2
const digits = (Math.floor(Math.random() * 9000000000) + 1000000000).toString();
3
return `PAX${digits}`;
4
};
5
6
module.exports = {
7
createSessionID,
8
};
9
And my unit test (again stripped down):
JavaScript
1
14
14
1
const { createSessionID } = require('../app/lib/populate-template-utilities');
2
3
describe('create XML for output files', () => {
4
5
const mockID = jest
6
.spyOn(createSessionID)
7
.mockImplementation(() => 'PAX123456');
8
9
it('should create a PAX File', async () => {
10
const result = await createFile();
11
expect(result).toEqual(getFile);
12
});
13
});
14
I want createSessionID to return ‘PAX123456’ and think mockID should do it, but it’s erroring with:
JavaScript
1
2
1
Cannot spy the undefined property because it is not a function; undefined given instead
2
Advertisement
Answer
The spyOn
method needs at least two parameters: object
and methodName
.
Try sth like this:
JavaScript
1
14
14
1
import * as populateTemplateUtils from "../sessionStuff";
2
import { createFile } from "../createFile";
3
4
describe('create XML for output files', () => {
5
it('should create a PAX File', async () => {
6
jest
7
.spyOn(populateTemplateUtils, 'createSessionID')
8
.mockReturnValue('PAX123456');
9
10
const result = await createFile();
11
expect(result).toEqual({"SessionID": "PAX123456"});
12
});
13
});
14
It all started to work when I changed the:
JavaScript
1
4
1
module.exports = {
2
createSessionID,
3
};
4
to:
JavaScript
1
2
1
export const createSessionID = () => {
2