Вы можете использовать jest.spyOn (object, methodName) для насмешки crypto.createHash
отдельно.
Например,
app.js
:
const crypto = require('crypto');
const express = require('express');
const app = express();
app.put('/api/engineer/confirm_mail/:token', async (req, res) => {
try {
const hashedToken = crypto.createHash('sha256').update(req.params.token).digest('hex');
console.log(hashedToken);
return res.status(202).send({ message: 'email verified' });
} catch (error) {
res.status(400).send({ error: error.message });
}
});
app.put('/example/:token', async (req, res) => {
const hashedToken = crypto.createHash('sha256').update(req.params.token).digest('hex');
console.log(hashedToken);
res.sendStatus(200);
});
module.exports = app;
app.test.js
:
const app = require('./app');
const request = require('supertest');
const crypto = require('crypto');
describe('61368162', () => {
it('should verify email', async () => {
const hashMock = {
update: jest.fn().mockReturnThis(),
digest: jest.fn().mockReturnValueOnce('encrypt 123'),
};
const createHashMock = jest.spyOn(crypto, 'createHash').mockImplementationOnce(() => hashMock);
const logSpy = jest.spyOn(console, 'log');
const engnr = { token: '123' };
const response = await request(app).put(`/api/engineer/confirm_mail/${engnr.token}`).send();
expect(createHashMock).toBeCalledWith('sha256');
expect(hashMock.update).toBeCalledWith('123');
expect(hashMock.digest).toBeCalledWith('hex');
expect(logSpy).toBeCalledWith('encrypt 123');
expect(response.statusCode).toBe(202);
expect(response.body).toMatchObject({ message: 'email verified' });
createHashMock.mockRestore();
logSpy.mockRestore();
});
it('should restore crypto methods', async () => {
const logSpy = jest.spyOn(console, 'log');
const response = await request(app).put('/example/123');
expect(jest.isMockFunction(crypto.createHash)).toBeFalsy();
expect(response.statusCode).toBe(200);
expect(logSpy).toBeCalledWith(expect.any(String));
logSpy.mockRestore();
});
});
результаты интеграционных испытаний с отчетом о покрытии:
PASS stackoverflow/61368162/app.test.js (13.621s)
61368162
✓ should verify email (44ms)
✓ should restore crypto methods (5ms)
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
encrypt 123
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 93.75 | 100 | 100 | 92.86 |
app.js | 93.75 | 100 | 100 | 92.86 | 12
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 15.707s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61368162