Вы должны использовать второй аргумент jest.mock (moduleName, factory, options) для насмешки над конструктором Busboy
.
Например
main.ts
:
import Busboy from 'busboy';
export function main() {
const busboy = new Busboy({});
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
console.log(
'File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype,
);
});
}
main.test.ts
:
import { main } from './main';
import Busboy from 'busboy';
jest.mock('busboy', () => {
const mBusboy = {
on: jest.fn(),
};
return jest.fn(() => mBusboy);
});
describe('59731700', () => {
let busboy;
beforeEach(() => {
busboy = new Busboy({});
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
it('should pass', () => {
const mockedEvenMap = {};
busboy.on.mockImplementation((event, callback) => {
mockedEvenMap[event] = callback;
});
const logSpy = jest.spyOn(console, 'log');
main();
mockedEvenMap['file']('a', 'b', 'c', 'd', 'e');
expect(logSpy).toBeCalledTimes(1);
});
});
Результаты модульных испытаний с отчетом о покрытии:
PASS src/stackoverflow/59731700/main.test.ts (16.143s)
59731700
✓ should pass (22ms)
console.log node_modules/jest-mock/build/index.js:860
File [a]: filename: c, encoding: d, mimetype: e
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
main.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 18.09s
Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59731700