在Redux中间件(Jest)中模拟节点模块

时间:2017-02-20 06:41:55

标签: mocking redux jestjs

我在Redux应用程序中从第三方节点模块模拟函数时遇到问题。

我正在尝试测试中间件函数,该函数拦截某个操作并从第三方npm包中调用函数。 (该模块是aws-iot-device-sdk,该函数建立与AWS IoT服务的websocket连接)

import awsIot from 'aws-iot-device-sdk'

// ...

const customMW = (store => {

  let websocket = null

  return next => action => {
    switch(action.type) {

      case 'CONNECT':

      websocket = awsIot.device({
        accessKeyId: action.accessKey
        // other params...
      })

      // Listen to events etc.
      break
      // ...
    }
  }
})

awsIot.device()建立了websocket连接,并且工作正常。

然而,当我尝试测试customMW函数时,awsIot.device()被调用,即使我试图模拟它(存储和下一个被适当地模拟):

test.js

describe('middleware test', () => {

  it('does something', () => {

    awsIot.device = jest.fn()
    action = { type: 'CONNECT' }
    customMW(store)(next)(action)
    // assertions...
  })
})

当我运行测试时,我收到错误' accessKey'未定义。因此,中间件正在运行原始awsIot.device()功能,该功能正在寻找' accessKey'作为行动的一部分传入。

我在其他地方成功地使用了这种模式。有谁知道为什么这个功能没有被嘲笑?

2 个答案:

答案 0 :(得分:2)

要模拟您要测试的文件中导入的内容,必须使用jest.mock。这将在实际导入之前覆盖导入的模块。如果你想检查你在测试中调用了awsIot.device,你还必须在测试中导入模块,然后像这样使用expect:

import awsIot from 'aws-iot-device-sdk'//only needed if you wanna test that device method was called

jest.mock('aws-iot-device-sdk', ()=>({
  device: jest.fn()
}))

describe('middleware test', () => {

  it('does something', () => {
    action = { type: 'CONNECT' }
    customMW(store)(next)(action)
    expect(awsIot.device).toHaveBeenCalled()
  })
})

答案 1 :(得分:0)

我设法通过结合Andreas'来解决这个问题。建议我必须提供正确的形状'我的测试中的行动。

action = {
  type: 'CONNECT',
  accessKeyId: 'testKey'
}

似乎模拟函数仍将读取传递给它的参数,如果存在引用错误则会出错。

相关问题