Skip to content

Commit

Permalink
feat(taro-h5): 增加 request 的测试用例
Browse files Browse the repository at this point in the history
  • Loading branch information
Chen-jj committed Jul 30, 2018
1 parent 90b2e0a commit bc8e2ab
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 81 deletions.
1 change: 1 addition & 0 deletions docs/native-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
| :-- | :-- | :-- | :-- | :-- |
| jsonp | String/Boolean || | 使用 jsonp,且使用此值作为回调函数名 |
| jsonpCache | Boolean || false | jsonp 请求 url 是否需要被缓存 |
| mode | String || same-origin | 是否允许跨域请求。有效值:no-cors, cors, same-origin |
| credentials | String || omit | 是否携带 Cookie。有效值:include, same-origin, omit |
| cache | String || default | 缓存模式。有效值:default, no-cache, reload, force-cache, only-if-cached |

Expand Down
1 change: 1 addition & 0 deletions packages/taro-h5/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"babel-jest": "^23.0.1",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"jest-fetch-mock": "^1.6.5",
"jest-localstorage-mock": "^2.2.0",
"jest-mock-console": "^0.3.5",
"mock-socket": "^7.1.0"
Expand Down
90 changes: 90 additions & 0 deletions packages/taro-h5/src/__test__/request-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/* eslint-disable */
import Taro from '../index.js'
Taro.initNativeApi(Taro)

global.fetch = require('jest-fetch-mock')

describe('request', () => {
beforeEach(() => {
fetch.resetMocks()
})

test('should return fetch data', () => {
fetch.once(JSON.stringify({ data: '12345' }))

return Taro.request({
url: 'https://github.com',
data: {
x: 123,
y: 'abc',
z: [1,2,3]
}
})
.then(res => {
expect(fetch.mock.calls[0][0]).toBe('https://github.com?x=123&y=abc&z=1%2C2%2C3')
expect(res.statusCode).toBe(200)
expect(res.data).toEqual({
data: '12345'
})
})
})

test('should return fetch data when options is url string', () => {
fetch.once(JSON.stringify({ data: '12345' }))

return Taro.request('https://github.com')
.then(res => {
expect(fetch.mock.calls[0][0]).toBe('https://github.com?')
expect(res.statusCode).toBe(200)
expect(res.data).toEqual({
data: '12345'
})
})
})

test('should set correct params', () => {
fetch.once(JSON.stringify({ data: '12345' }), { status: 201 })

return Taro.request({
url: 'https://github.com',
method: 'POST',
data: {
arg: 123
},
header: {
'A': 'CCC'
},
mode: 'cors',
cache: 'no-cache',
credentials: 'include'
})
.then(res => {
expect(fetch.mock.calls[0][0]).toBe('https://github.com')
expect(fetch.mock.calls[0][1]).toEqual({
method: 'POST',
body: {
arg: 123
},
headers: {
'A': 'CCC'
},
mode: 'cors',
cache: 'no-cache',
credentials: 'include'
})
expect(res.statusCode).toBe(201)
expect(res.data).toEqual({
data: '12345'
})
})
})

test('should catch error', () => {
fetch.mockReject(new Error('fake error message'))

return Taro.request('https://github.com')
.catch(err => {
expect(err.message).toBe('fake error message')
})
})
})
71 changes: 71 additions & 0 deletions packages/taro-h5/src/api/request/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import jsonpRetry from 'jsonp-retry'
import { serializeParams } from '../utils'

function generateRequestUrlWithParams (url, params) {
params = typeof params === 'string' ? params : serializeParams(params)
url += (~url.indexOf('?') ? '&' : '?') + `${params}`
url = url.replace('?&', '?')
return url
}

export default function request (options) {
options = options || {}
if (typeof options === 'string') {
options = {
url: options
}
}
let url = options.url
const params = {}
const res = {}
if (options.jsonp) {
params.params = options.data
params.cache = options.jsonpCache
if (typeof options.jsonp === 'string') {
params.name = options.jsonp
}
return jsonpRetry(url, params)
.then(data => {
res.statusCode = 200
res.data = data
return res
})
}
params.method = options.method || 'GET'
const methodUpper = params.method.toUpperCase()
params.cache = options.cache || 'default'
if (methodUpper === 'GET' || methodUpper === 'HEAD') {
url = generateRequestUrlWithParams(url, options.data)
} else {
params.body = options.data
}
if (options.header) {
params.headers = options.header
}
if (options.mode) {
params.mode = options.mode
}
params.credentials = options.credentials
return fetch(url, params)
.then(response => {
res.statusCode = response.status
res.header = {}
response.headers.forEach((val, key) => {
res.header[key] = val
})
if (options.responseType === 'arraybuffer') {
return response.arrayBuffer()
}
if (options.dataType === 'json' || typeof options.dataType === 'undefined') {
return response.json()
}
if (options.responseType === 'text') {
return response.text()
}
return Promise.resolve(null)
})
.then(data => {
res.data = data
return res
})
}
13 changes: 12 additions & 1 deletion packages/taro-h5/src/api/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,20 @@ function errorHandler (fail, complete) {
}
}

const enc = encodeURIComponent

function serializeParams (params) {
if (!params) {
return ''
}
return Object.keys(params)
.map(item => (`${item}=${enc(params[item])}`)).join('&')
}

export {
shouleBeObject,
getParameterError,
inlineStyle,
errorHandler
errorHandler,
serializeParams
}
71 changes: 1 addition & 70 deletions packages/taro-h5/src/native-api.js
Original file line number Diff line number Diff line change
@@ -1,81 +1,12 @@
import 'whatwg-fetch'
import jsonpRetry from 'jsonp-retry'

import { onAndSyncApis, noPromiseApis, otherApis } from '@tarojs/taro'
import { serializeParams } from './util'
import { createSelectorQuery } from './api/createSelectorQuery'
import request from './api/request'
import * as storage from './api/storage'
import * as interactive from './api/interactive'
import webSocket from './api/webSocket'

function generateRequestUrlWithParams (url, params) {
params = typeof params === 'string' ? params : serializeParams(params)
url += (~url.indexOf('?') ? '&' : '?') + `${params}`
url = url.replace('?&', '?')
return url
}

function request (options) {
options = options || {}
if (typeof options === 'string') {
options = {
url: options
}
}
let url = options.url
const params = {}
const res = {}
if (options.jsonp) {
params.params = options.data
params.cache = options.jsonpCache
if (typeof options.jsonp === 'string') {
params.name = options.jsonp
}
return jsonpRetry(url, params)
.then(data => {
res.statusCode = 200
res.data = data
return res
})
}
params.method = options.method || 'GET'
const methodUpper = params.method.toUpperCase()
params.cache = options.cache || 'default'
if (methodUpper === 'GET' || methodUpper === 'HEAD') {
url = generateRequestUrlWithParams(url, options.data)
} else {
params.body = options.data
}
if (options.header) {
params.headers = options.header
}
if (options.mode) {
params.mode = options.mode
}
params.credentials = options.credentials
return fetch(url, params)
.then(response => {
res.statusCode = response.status
res.header = {}
response.headers.forEach((val, key) => {
res.header[key] = val
})
if (options.responseType === 'arraybuffer') {
return response.arrayBuffer()
}
if (options.dataType === 'json' || typeof options.dataType === 'undefined') {
return response.json()
}
if (options.responseType === 'text') {
return response.text()
}
return Promise.resolve(null)
}).then(data => {
res.data = data
return res
})
}

function processApis (taro) {
const weApis = Object.assign({ }, onAndSyncApis, noPromiseApis, otherApis)
Object.keys(weApis).forEach(key => {
Expand Down
10 changes: 0 additions & 10 deletions packages/taro-h5/src/util.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const enc = encodeURIComponent

export function isEmptyObject (obj) {
if (!obj) {
return false
Expand Down Expand Up @@ -55,11 +53,3 @@ export function getPrototypeChain (obj) {
}
return protoChain
}

export function serializeParams (params) {
if (!params) {
return ''
}
return Object.keys(params)
.map(item => (`${item}=${enc(params[item])}`)).join('&')
}

0 comments on commit bc8e2ab

Please sign in to comment.