Jest - 测试 redux 动作

Jest - testing redux actions

我正在尝试使用 Jest 测试我的应用程序的 redux 操作。我查看了测试站点 @ redux.js.org 和其他论坛帖子,但我不明白为什么我会收到错误,我想我不明白模拟是如何工作的。

我的动作在index.js:

export const setResponse = (res) => {
    return {
        type: 'RESPONSE_RECEIVED',
        payload: res
    }
};

我的测试是actions.test.js:

import * as actions from '../src/client/scripts/actions/index'

describe('actions', () => {
  it('should create an action to receive a response', () => {
    const payload = {response: 'solr_json'};
    const expectedAction = {
      type: 'RESPONSE_RECEIVED',
      payload
    }
    expect(actions.setResponse(payload)).toEqual(expectedAction)
  })
});

我得到了错误 'Expected undefined to equal Object...' 所以我认为 actions.setResponse 不存在,所以我打印出来 actions.setResponse 它看起来像这样:

{ [Function: setResponse]
  _isMockFunction: true,
  getMockImplementation: [Function],
  mock: { calls: [], instances: [] },
  mockClear: [Function],
  mockReturnValueOnce: [Function],
  mockReturnValue: [Function],
  mockImplementationOnce: [Function],
  mockImpl: [Function],
  mockImplementation: [Function],
  mockReturnThis: [Function] }

看来函数就在那里,我如何在 Jest 测试中实际调用函数?就算我改

export const setResponse = (res) =>

export function setResponse(res)

(所以它与 redux.js.org 教程的格式相同)我得到同样的错误。作为参考,这是我 package.json:

的笑话部分
"jest": {
    "scriptPreprocessor": "node_modules/babel-jest",
    "testFileExtensions": [
      ".test.js"
    ],
    "testPathDirs": [
      "__tests__"
    ],
    "moduleFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "node_modules/react",
      "node_modules/react-addons-test-utils",
      "node_modules/react-dom"
    ]
  }

感谢您的帮助

问题似乎是您要测试的模块被模拟了,因为您使用了 unmockedModulePathPatterns。来自文档:

An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns in this list, it will not be automatically mocked by the module loader.

我猜如果你删除这一行模块不会自动模拟。通常使用 jest.mock 在测试中直接模拟你想模拟的东西更容易。或者您将源文件夹添加到 unmockedModulePathPatterns.

的列表中