- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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)))
}
}
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)
})
})
Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream
最佳答案
这个答案来得太晚了,但我想做类似的事情,我想在这里发布一个解决方案,其他人可能会偶然发现并发现有用。
这里的主要问题是 nock 模拟网络请求而不是 Javascript 库。 FormData
是一个 Javascript 对象,在发出网络请求时最终会转换为文本。到了FormData
对象使其成为 nock,它已被转换为 string
或 Buffer
,因此您看到的错误。 nock 无法使用 FormData
比较的对象。
你有几个选择:
1. 最简单的解决方案
只是不要匹配 PUT
中的数据要求。您 mock 的原因是因为您不希望发出真正的 HTTP 请求,但希望返回虚假的响应。 nock
只模拟一次请求,所以如果你模拟所有 PUT
对 /user/photo
的请求nock 会捕获它,但仅用于该测试:
nock(API_URL, {
reqheaders: {
'x-access-token': token
}
}).put('/user/photo')
.reply(200, {body: {}})
nock(API_URL, {
reqheaders: {
'x-access-token': token
}
}).put('/user/photo', /Content-Disposition\s*:\s*form-data\s*;\s*name="file"\s*;\s*filename="filename.txt"/i)
.reply(200, {body: {}})
export function updateUserPhoto (file, tags, token) {
const data = new FormData()
data.append('file', file)
data.append('tags', tags)
...
const file = new File(Array.from('file contents'), 'filename.txt', {
type: 'text/plain',
lastModified: new Date()
})
parse-multipart-data
是一个相当简单的解析器,您可以使用:
it('creates USER_UPDATE_SUCCESS when updating user photo has been done', () => {
const store = mockStore(Map())
const file = new File(Array.from('file content'), 'filename.txt', {
type: 'text/plain',
lastModified: new Date()
})
nock(API_URL, {
reqheaders: {
'x-access-token': token
}
}).put('/user/photo', function (body) { /* You cannot use a fat-arrow function since we need to access the request headers */
// Multipart Data has a 'boundary' that works as a delimiter.
// You need to extract that
const boundary = this.headers['content-disposition']
.match(/boundary="([^"]+)"/)[1];
const parts = multipart.Parse(Buffer.from(body),boundary);
// return true to indicate a match
return parts[0].filename === 'filename.txt'
&& parts[0].type === 'text/plain'
&& parts[0].data.toString('utf8') === 'file contents'
&& parts[1].name === 'tags[]'
&& parts[1].data.toString('utf8') === 'tag1'
&& parts[2].name === 'tags[]'
&& parts[2].data.toString('utf8') === 'tag2';
})
.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, ['tag1', 'tag2'], token))
.then(() => {
// return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
})
关于reactjs - Redux 使用 jest、nock、axios 和 jsdom 测试 multipart/form-data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46818751/
这是在后端和前端工作正常的 Express Route 代码。 //编辑/更新容器类型 by_id - 工作 router.put("/:id", (req, res, next) => { Ve
当发出请求但未被模拟时,我得到一个错误:Error: Nock: No match for request 但这并没有使测试失败。有没有办法确保没有发出模拟请求? 最佳答案 您可以从 nock noc
如何查看nock是否与请求匹配?有没有一种方法可以在控制台上记录有关 nock 是否与正在发出的请求匹配的信息? 最佳答案 log功能在较新版本的 nock 上不再可用,例如v13.0.0 但你可以设
我正在编写与 PayPal 经典 API 交互的代码。此交互的第一部分是向 PayPal 发送请求并从他们那里获取 token 。为此,我使用简单的 https 请求: function makePa
我一直在编写一些单元测试,我注意到我似乎找不到测试异步函数的好方法。所以我找到了诺克。看起来很酷,只要它有效。我显然错过了一些东西...... import nock from 'nock'; imp
使用 nock 模拟请求链的简单示例。 const request = require('request-promise'); module.exports = () => {
我不确定 nock 是否支持在调用拦截器时使用回调/事件发射器等待或通知。 例如: const scope = nock(config.research.url)
我不确定 nock 是否支持在调用拦截器时使用回调/事件发射器等待或通知。 例如: const scope = nock(config.research.url)
我正在使用 Nock 拦截 http 请求。 测试.js: const nock = require('nock'); const server = require('../server'); con
这是我的一个拦截函数现在的样子: interceptWithError() { nock(baseUrl) .get(/.*/) .replyWithError(500); n
我正在使用 nock 库来 stub 我的 http 调用。不同的测试文件 require('nock') 并进行 stub 。如果每个测试单独运行,则所有测试都通过。但是,如果所有测试一起运行,后面
我正在尝试使用业力服务器和诺克创建一些基本测试。似乎 nock 根本没有拦截我的请求,有人知道吗?我无法弄清楚缺少什么。我仍然得到真实的数据。 nock('https://api.github.com
我正在尝试使用 SuperTest 自动化一些 REST 服务。该服务是一个 POST 调用,它在内部调用另一个第三方服务的 GET 方法。我正在尝试模拟第三方服务以提高测试效率并减少测试执行时间。我
我按照 redux.org 的基本示例来测试异步操作 action.js 我的代码是这样的: import axios from 'axios' export function getGoodData
我有一个 Node.js 服务,它在向用户返回响应之前调用外部 API 来收集一些数据。我想模拟这个外部 API,以便测试我的服务,但不幸的是,我得到的响应没有内容(只有状态 200)。这是我的测试:
我正在尝试运行下面的一段代码: const nock = require('nock'); const request = require('request-promise'); nock('http
我有验证 response.connection.remoteAddress 的应用程序代码不是本地 IP,但在使用 nock 时 response.connection只是一个没有 remoteAd
我目前正在使用 node-fetch 和 nock 作为位于 Angular 项目之上的快速服务器。 我有以下正在调用 api 的中间件: export const middleware = asyn
我正在尝试模拟包含问号但不属于查询字符串的路径,例如: https://example.com/index.php?/api/v2/get-item/1 Nock 正在对问号处的路径进行切片,并期望我
我正在尝试使用 nock 对针对 Oanda 的交易 API 编写的代码运行回测。为此,我需要模拟流式价格 API(请参阅 http://developer.oanda.com/rest-practi
我是一名优秀的程序员,十分优秀!