Sagas通话的JEST测试

问题描述 投票:1回答:1

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

欢迎任何反馈。

reactjs unit-testing react-redux jest redux-saga
1个回答
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() }))
  };
});`
© www.soinside.com 2019 - 2024. All rights reserved.