【发布时间】: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]}}
function 和 context 不匹配。我做错了什么?我不确定问题是否来自 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