【发布时间】:2018-03-30 20:00:38
【问题描述】:
我正在使用 jest+nock+jsdom 模块来测试我的 React\Redux 应用程序。 我需要测试这个异步操作函数:
export function updateUserPhoto (file, token) {
const data = new FormData()
data.append('file', file)
return dispatch => {
dispatch(userPutPhotoRequest())
return axios({
method: 'PUT',
headers: {
'x-access-token': token
},
data: data,
url: API_URL + '/user/photo'
})
.then(res => dispatch(userPutPhotoSuccess(res.data)))
.catch(err => dispatch(userPutPhotoFilure(err)))
}
}
所以我使用 jsdom 将 FormData 和 File 对象提供给测试:
const {JSDOM} = require('jsdom')
const jsdom = (new JSDOM(''))
global.window = jsdom.window
global.document = jsdom.window.document
global.FormData = jsdom.window.FormData
const File = jsdom.window.File
global.File = jsdom.window.File
这是测试“上传照片”功能的方法:
it('creates USER_UPDATE_SUCCESS when updating user photo has been done', () => {
const store = mockStore(Map())
const file = new File([''], 'filename.txt', {
type: 'text/plain',
lastModified: new Date()
})
const expectedFormData = new FormData()
expectedFormData.append('file', file)
nock(API_URL, {
reqheaders: {
'x-access-token': token
}
}).put('/user/photo', expectedFormData)
.reply(200, {body: {}})
const expectedActions = [
{
type: ActionTypes.USER_PUT_PHOTO_REQUEST
},
{
type: ActionTypes.USER_PUT_PHOTO_SUCCESS,
response: {
body: {}
}
}
]
return store.dispatch(actions.updateUserPhoto(file, token))
.then(() => {
// return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
})
我使用 nock 来模拟 axios 请求,使用 redux-mock-store 来模拟 Redux 存储。 创建 File 和 FormData 对象以将其与来自 axios 的响应进行比较。 然后我调用动作函数将文件和令牌作为参数传递。
在生产动作功能工作和调度动作成功正常。但在测试中我收到错误:
Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream
当我在数据测试通过时传入 axios 空对象时,FormData 对象出现问题。 如何以适当的方式模拟 axios 的 FormData 对象以使该测试正常工作?
【问题讨论】:
-
你发现了吗?我正在尝试做类似的事情,但我得到了
FormData is not a constructor。还需要以某种方式模拟 FormData。 -
不幸的是我没有找到解决这个问题的方法。所以我能做的就是评论这个测试。
标签: reactjs redux jestjs axios form-data