如何使用jestJS模拟嵌套函数

时间:2018-10-16 08:25:48

标签: javascript unit-testing jestjs

我正在尝试使用jestJS为此功能编写一个测试,但是在模拟socket.emit()getPwmDutyCycle()函数时遇到了一些问题:

module.exports = async (app, socket) => {
  const res = []
  const array = ['some', 'example', 'elements']
  array.map((elm, index) => {
    res.push(app.locals['target' + (index + 1)].getPwmDutyCycle())
  })
  socket.emit('status', res)
}

这是我想出的:

const status = require('../lib/status.js')

test('should emit dc values', () => {
  const app = {
    locals: {
      target1: 1,
      target2: 2,
      target3: 3
    }
  }
  const socket = { emit: jest.fn() }
  status(app, socket)
  expect(socket.emit).toHaveBeenCalled()
  expect(socket.emit.mock.calls[0][0]).toBe('status')
  expect(socket.emit.mock.calls[1][0]).toBe([1, 2, 3])
})

1 个答案:

答案 0 :(得分:0)

您的app存根未使用getPwmDutyCycle方法:

  const app = {
    locals: {
      target1: { getPwmDutyCycle: () => 1},
      target2: { getPwmDutyCycle: () => 2},
      target3: { getPwmDutyCycle: () => 3}
    }
  }