【问题标题】:JEST testing of a Sagas callSagas 调用的 JEST 测试
【发布时间】:2017-08-13 12:42:51
【问题描述】:

在 JEST 测试框架中是全新的,我在 sagas 测试中面临一个非常直截了当的问题。环顾四周,我发现为了测试一个调用 API 的 saga,我必须使用 jest.mock 模拟它。

所以这是我在 shell 中的代码:

export function* getSomething() {
  const url = 'http://localhost:4000/users/'
  const list = yield call(whatwgFetch, url)
  yield put(setListClients(list))
}

setListClients 是一个动作,whatwgFetch 从 utils/fetch 文件中导出,如下所示:

export const whatwgFetch = (url, options) => {
  return fetch(url, options)
    .then(response => checkStatus(response).text())
    .then(body => JSON.parse(body))
}

我的测试看起来像:

import { call } from 'redux-saga/effects';
import { setListClients } from 'app/actions'
import { getSomething } from './watchSomething'

const whatwgFetch = jest.mock('utils/fetch')

describe('Testing a saga', () => {
  const generator = getSomething()

  it('must call whatwgFetch', () => {
    const testValue = generator.next().value
    expect(testValue).toEqual(call(whatwgFetch, 'http://localhost:4000/users/'))
  })
})

问题,我的测试输出告诉我:

Expected value to equal:
  {"@@redux-saga/IO": true, "CALL": {"args": ["http://localhost:4000/users/"], "context": undefined, "fn": [Function bound fn]}}
Received:
  {"@@redux-saga/IO": true, "CALL": {"args": ["http://localhost:4000/users/"], "context": null, "fn": [Function anonymous]}}

functioncontext 不匹配。我做错了什么?我不确定问题是否来自 whatwgFetch 的模拟、whatwgFetch 本身、调用等......

欢迎任何反馈。

【问题讨论】:

  • 在我看来 jest.mock('utils/fetch') 只是一个与原始 whatwgFetch 不同的函数。我认为你不需要在这种情况下模拟它,因为它实际上并没有被调用。
  • 嘿马丁感谢您的评论。我 export default whatwgFetch 来自 utils/fetch.js 文件。他们怎么不一样?是的,它没有被调用,所以你建议我直接导入它并按原样测试?
  • 重要的不是你如何导出它,而是你如何导入它。我怀疑调用 jest.mock('utils/fetch') 会用开玩笑的模拟函数替换 fetch 函数。至于测试,是的,我认为按原样测试它可能会很好。

标签: reactjs unit-testing react-redux jestjs redux-saga


【解决方案1】:

试试这样的:

`jest.mock('redux-saga/effects', () => {
  const originalModule = jest.requireActual('redux-saga/effects');

  return {
    __esModule: true,
    ...originalModule,
    call: jest.fn((fn, ...rest) => ({ args: rest, fn: jest.fn() }))
  };
});`

【讨论】:

    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 2019-09-21
    • 2020-05-02
    • 2023-02-07
    • 2016-01-19
    • 1970-01-01
    • 2019-04-21
    • 2019-12-28
    相关资源
    最近更新 更多