我有一个具有main-process.js
和child-process.js
的Node.js应用程序。
main-process.js
看起来像这样:
var childProcess = require('child_process');
var job = childProcess.spawn('node', ["child-process.js"], {
detached = true,
stdio: ['ipc']
});
我的child-process.js
执行了一些任务,并通知父进程有关其状态的信息,它使用:
exports.init = function() {
//some processing here
process.send({status: 'success or pending'});
}
现在我想使用jasmine-node对child-process.js
进行单元测试,但是当我从规范中调用方法init()
时,jasmine-node
会抛出错误:
TypeError: Object #<process> has no method 'send'
有没有办法模拟process
变量?换句话说,我该如何对这种情况进行单元测试?
答案 0 :(得分:0)
有什么方法可以模拟过程变量?换句话说,如何对这种情况进行单元测试?
没有必要在process.send()
中导出child-process.js
功能。
您可以将process.send()
放在身体的任何位置,以便与main-process.js
进行交流
我已经使用Jasmine成功运行了以下代码:
main-process.js
var childProcess = require('child_process');
// set an infinite loop that keeps main-process running endlessly
setInterval(() => null, 5000)
// spawn child process
var job = childProcess.spawn('node', ["child-process.js"], {
detached: true,
stdio: ['ipc']
});
// listen to the events returned by child process
job.on('message', (code, signal) =>
console.log('[MAIN] received the ff from child process:', {code, signal}, 'at', new Date())
)
// export the job object, which is an event emitter that can be tested by Jasmine pkg
module.exports = job
child-process.js
const message = {
message: `I'm working on it...`,
status: 'success or pending'
}
// send a message to the parent every half second
setInterval(() => process.send(message), 500)
spec.js
const main = require('../main-process')
describe('main process', () =>
it('should receive messages from spawned child process', (done) => {
let eventCount = 0
main.on('message', (code, signal) => {
console.log('[JASMINE] received the event')
eventCount++
if (eventCount >= 5) {
done()
}
})
})
)
输出
$ npm test
> so-jasmine-test@1.0.0 test C:\Users\jonathanlopez\nodejs\so-jasmine-test
> jasmine
Randomized with seed 29172
Started
[MAIN] received the ff from child process: { code:
{ message: 'I\'m working on it...',
status: 'success or pending' },
signal: undefined } at 2018-10-17T08:50:51.559Z
[JASMINE] received the event
[MAIN] received the ff from child process: { code:
{ message: 'I\'m working on it...',
status: 'success or pending' },
signal: undefined } at 2018-10-17T08:50:52.060Z
[JASMINE] received the event
[MAIN] received the ff from child process: { code:
{ message: 'I\'m working on it...',
status: 'success or pending' },
signal: undefined } at 2018-10-17T08:50:52.562Z
[JASMINE] received the event
[MAIN] received the ff from child process: { code:
{ message: 'I\'m working on it...',
status: 'success or pending' },
signal: undefined } at 2018-10-17T08:50:53.064Z
[JASMINE] received the event
[MAIN] received the ff from child process: { code:
{ message: 'I\'m working on it...',
status: 'success or pending' },
signal: undefined } at 2018-10-17T08:50:53.565Z
[JASMINE] received the event
.
1 spec, 0 failures
Finished in 2.736 seconds
Randomized with seed 29172 (jasmine --random=true --seed=29172)