我正在编写单元测试,并在包'child_process'中模拟'exec'方法。
__嘲笑__ / child_process.js
const child_process = jest.genMockFromModule('child_process');
child_process.exec = jest.fn()
module.exports = child_process;
这是测试文件:
const fs = require('fs-extra'),
child_process = require('child_process'),
runCassandraMigration = require('../../lib/runCassandraMigration.js')
const defaultArguments = () => {
return {
migration_script_path: './home',
logger: {
error: function () {}
}
};
}
jest.mock("fs-extra")
jest.mock("child_process")
describe('Running cassandra migration tests', function () {
describe('successful flow', function () {
it('Should pass without any errors ', async function () {
let args = defaultArguments();
let loggerSpy = jest.spyOn(args.logger, 'error')
fs.remove.mockImplementation(() => {Promise.resolve()})
child_process.exec.mockImplementation(() => {Promise.resolve()})
await runCassandraMigration(args.migration_script_path, args.logger)
});
});
当我运行测试时,我收到以下错误:
child_process.exec.mockImplementation is not a function
我测试的模块
const fs = require('fs-extra')
const promisify = require('util').promisify
const execAsync = promisify(require('child_process').exec)
module.exports = async (migration_script_path, logger) => {
try {
console.log()
const {stdout, stderr} = await execAsync(`cassandra-migration ${migration_script_path}`)
logger.info({stdout: stdout, stderr: stderr}, 'Finished runing cassandra migration')
await fs.remove(migration_script_path)
} catch (e) {
logger.error(e, 'Failed to run cassandra migration')
throw Error()
}
}
请告知。
答案 0 :(得分:0)
迟到... answer ?...
昨天我遇到了同样的错误,问题是我没有在测试文件中调用jest.mock('child_process')
。
笑话documentation说,当嘲笑Node的核心模块调用jest.mock('child_process') is required
时。我看到您这样做了,但由于某种原因它无法正常工作(也许Jest没有将其提升到顶部)。
无论如何,在Jest版本24.9.0中,我没有遇到child_process.exec.mockImplementation is not a function
错误,但是由于您的测试没有很好地实现,所以出现了一些其他错误。
为使您的测试正常进行,我:
在info: function () {},
内添加了logger
将exec
的实现更新为child_process.exec.mockImplementation((command, callback) => callback(null, {stdout: 'ok'}))
并且(对于通过测试不是必须的)将fs.remove
的实现更新为fs.remove.mockImplementation(() => Promise.resolve())
赞:
const fs = require('fs-extra'),
child_process = require('child_process'),
runCassandraMigration = require('./stack')
const defaultArguments = () => {
return {
migration_script_path: './home',
logger: {
info: function () {},
error: function () {}
}
};
}
jest.mock("fs-extra")
jest.mock("child_process")
describe('Running cassandra migration tests', function () {
describe('successful flow', function () {
it('Should pass without any errors ', async function () {
let args = defaultArguments();
let loggerSpy = jest.spyOn(args.logger, 'error')
fs.remove.mockImplementation(() => Promise.resolve())
child_process.exec.mockImplementation((command, callback) => callback(null, {stdout: 'ok'}))
await runCassandraMigration(args.migration_script_path, args.logger)
});
});
});