英文:
nodejs Jest testing exec.stdout.on('data',data)
问题
尝试测试一个包含child_process库exec的函数。
const { exec } = require('child_process')
const randomFunc = () => { 
  const newSync = exec('要执行的一些命令')
  newSync.stdout.on('data', data => {
   console.log(data.toString())
  })
}
testfile:
const {randomFunc} = require(randomFuncFile)
const { exec } = require('child_process')
jest.mock('child_process')
it('测试', () => {
    const readStreamObject = {
      on: jest.fn().mockImplementation(function (event, handler) {
        handler('streaming ')
      })
    }
   exec.mockImplementation(data => ({stdout: readStreamObject}))
   randomFunc()
   expect(exec.stdout.on).toHaveBeenCalled()
}
我得到以下错误:
TypeError: Cannot read properties of undefined (reading 'on')
一些提示会很有帮助。
英文:
Trying to to test a function the incorporates the exec of child_process library.
const { exec } = require('child_process')
const randomFunc = () => { 
  const newSync = exec('some command to execute')
  newSync.stdout.on('data', data => {
   console.log(data.toString())
  })
}
testfile:
const {randomFunc} = require(randomFuncFile)
const { exec } = require('child_process')
jest.mock('child_process')
it('test', () => {
    const readStreamObject = {
      on: jest.fn().mockImplementation(function (event, handler) {
        handler('streaming ')
      })
    }
   exec.mockImplementation(data => ({stdout: readStreamObject})
   randomFunc()
   expect(exec.stdout.on).toHaveBeenCalled()
}
I'm getting
> TypeError: Cannot read properties of undefined (reading 'on')
some tips would be great.
答案1
得分: 1
你可以通过模拟的exec()函数获取模拟执行的stdout,方法是使用exec.mock.results[0].value.stdout,详见这里。
index.js:
const { exec } = require('child_process');
const randomFunc = () => {
  const newSync = exec('要执行的某个命令');
  newSync.stdout.on('data', (data) => {
    console.log(data.toString());
  });
};
module.exports = { randomFunc };
index.test.js:
const { exec } = require('child_process');
const { randomFunc } = require('./');
jest.mock('child_process');
it('测试', () => {
  const mStdout = {
    on: jest.fn().mockImplementation(function (event, handler) {
      handler('流数据');
    }),
  };
  exec.mockImplementation(() => ({ stdout: mStdout }));
  randomFunc();
  // expect(mStdout.on).toHaveBeenCalled();
  // 或者
  expect(exec.mock.results[0].value.stdout.on).toHaveBeenCalled();
});
测试结果:
 PASS  stackoverflow/75036469/index.test.js (8.403 s)
  ✓ test (15 ms)
  console.log
    流数据
      at stackoverflow/75036469/index.js:6:13
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.016 s
英文:
You can get the mock stdout returned by mocked exec() function via exec.mock.results[0].value.stdout, See mockFn.mock.results
index.js:
const { exec } = require('child_process');
const randomFunc = () => {
  const newSync = exec('some command to execute');
  newSync.stdout.on('data', (data) => {
    console.log(data.toString());
  });
};
module.exports = { randomFunc };
index.test.js:
const { exec } = require('child_process');
const { randomFunc } = require('./');
jest.mock('child_process');
it('test', () => {
  const mStdout = {
    on: jest.fn().mockImplementation(function (event, handler) {
      handler('streaming');
    }),
  };
  exec.mockImplementation(() => ({ stdout: mStdout }));
  randomFunc();
  // expect(mStdout.on).toHaveBeenCalled();
  // or
  expect(exec.mock.results[0].value.stdout.on).toHaveBeenCalled();
});
Test result:
 PASS  stackoverflow/75036469/index.test.js (8.403 s)
  ✓ test (15 ms)
  console.log
    streaming
      at stackoverflow/75036469/index.js:6:13
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.016 s
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论