I have a function that takes in an object, manipulates it, checks that the manipulated object still contains data, then iterates through the object’s keys using Object.keys
/ forEach
and passes the data to another function. This all works, but Jest is saying I don’t have coverage for the Object.keys
lines, despite several tests that test this function successfully:
My main file:
export const assignAndTrigger = (tags) => {
const tagObject = assignTagObject(tags);
if (tagObject) {
Object.keys(tagObject).forEach((tagArrays) => {
triggerTags(tagObject[tagArrays]);
});
}
};
export const triggerTags = (tags) => {
//do some stuff with the tags
});
My test file is saying I do not have coverage for lines 5 and 6 in the above.
I’ve tried setting up specific tests to confirm that the triggerTags object is firing successfully, but it doesn’t seem to be working as I intend. Here I’m mocking the functions and expecting triggerTags to be called:
import { assignAndTrigger } from '../../src/mainFile';
import * as mainFile from '../../src/mainFile';
jest.mock('../../src/mainFile', () => ({
triggerTags: jest.fn(),
assignAndTrigger: jest.fn()
}));
describe('assignAndTrigger()', () => {
beforeEach(() => {
// mock triggerTags function
jest.spyOn(mainFile, 'triggerTags');
});
afterEach(() => {
jest.restoreAllMocks();
jest.clearAllMocks();
delete window.digitalData;
});
it('should call triggerTags function', () => {
const tags = {
Tags: {
Item1: [{ tag_name: 'AB-0001', custom_parameters: {} }],
Item2: [{ tag_name: 'CD-0001', custom_parameters: {} }],
},
};
assignAndTrigger(tags);
expect(triggerTags).toHaveBeenCalled();
});
});
In another test I tried spyOn, but that seems to not work either, as. I get the error: Property
triggerTags does not exist in the provided objec
:
it('should run assignTagObject and trigger tags', () => {
const spy = jest.spyOn(assignAndTrigger, 'triggerTags');
assignAndTrigger(tags);
expect(spy).toHaveBeenCalled();
});