JEST测试Sagas呼叫

时间:2017-08-13 12:42:51

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

在JEST测试框架中是全新的,我面临一个非常直接的问题,一个传奇测试。环顾四周,我发现为了测试一个进行API调用的传奇,我必须使用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本身,调用等......

欢迎任何反馈。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

`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() }))
  };
});`