在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]}}
function
和context
不匹配。我做错了什么?我不确定问题是来自于whatwgFetch的模拟,whatwgFetch本身,调用等......
欢迎任何反馈。
答案 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() }))
};
});`