node.js Jest 测试 exec.stdout.on(‘data’, data)

huangapple go评论79阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年1月7日 06:01:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75036469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定