Вы не можете использовать jest.mock
в области действия функции. Это следует использовать в объеме модуля. Вместо использования jest.mock
внутри функции тестового примера, вы должны использовать jest.doMock (moduleName, factory, options)
Например server.js
:
const express = require('express');
const app = express();
const server = app.listen(8080, '127.0.0.1').on('error', (err) => {
console.log(err);
});
module.exports = server;
server.test.js
:
describe('60451082', () => {
it('should pass', () => {
const mError = new Error('network');
const appMock = {
listen: jest.fn().mockReturnThis(),
on: jest.fn().mockImplementationOnce((event, handler) => {
handler(mError);
}),
};
jest.doMock('express', () => jest.fn(() => appMock));
const logSpy = jest.spyOn(console, 'log');
const express = require('express');
require('./server');
expect(express).toBeCalledTimes(1);
expect(appMock.listen).toBeCalledWith(8080, '127.0.0.1');
expect(appMock.on).toBeCalledWith('error', expect.any(Function));
expect(logSpy).toBeCalledWith(mError);
});
});
Результаты модульных испытаний со 100% покрытием:
PASS stackoverflow/60451082/server.test.js
60451082
✓ should pass (19ms)
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
Error: network
at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60451082/server.test.js:3:20)
at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:100:37)
at resolve (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
at new Promise (<anonymous>)
at mapper (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at promise.then (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
at process._tickCallback (internal/process/next_tick.js:68:7)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
server.js | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.444s, estimated 10s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60451082