I have a function:
export class Processor {
public static async process(info) {
return Promise.resolve('item processed');
}
}
import { Processor } from "./processor";
export const execute = (event, context) => {
const records = event.Records;
records.map(async (record) => {
return await processRecord(record.body.info);
});
async function processRecord(info) {
try {
console.log('before process');
await Processor.process(info);
console.log('after process');
} catch (e) {
throw new Error('Processing error');
}
}
};
Then I have a test:
import { execute } from "./execute";
import { Processor } from "./processor";
jest.mock("./Processor");
const mockProcessor = jest.mocked(Processor, false);
describe("Execute", () => {
it("should process info", () => {
const processSpy = jest.spyOn(mockProcessor, "process").mockResolvedValueOnce("test-return");
const result = await execute({Records: [{body: {info: "test-info"}}]}, {});
expect(processSpy).toHaveBeenCalled();
});
});
The test fails on the process spy, although 'before process' and 'after process' logs are displayed. Where did I make a mistake ?
You don't need to use jest.mock('./Processor'), use jest.spyOn(Processor, 'process') is enough.
import { execute } from './execute';
import { Processor } from './processor';
describe('Execute', () => {
it('should process info', async () => {
const processSpy = jest.spyOn(Processor, 'process').mockResolvedValueOnce('test-return');
await execute({ Records: [{ body: { info: 'test-info' } }] }, {});
expect(processSpy).toHaveBeenCalled();
});
});