我想在请求返回中测试错误.我在测试中使用nock,如何强迫Nock引发错误?我想实现100%的测试覆盖率,并且需要测试错误的分支
request('/foo', function(err, res) {
if(err) console.log('boom!');
});
Run Code Online (Sandbox Code Playgroud)
永远不要进入if err分支.即使命中错误是一个有效的响应,我的测试中的Nock行看起来像这样
nock('http://localhost:3000').get('/foo').reply(400);
Run Code Online (Sandbox Code Playgroud)
编辑: 感谢您的一些评论:
我需要模拟客户端HTTP请求.我isomorphic-fetch在客户端使用mocha,我正在使用并nock进行测试和嘲笑.我的所有客户请求都基于相对路径.由于这个原因,我无法提供主机名nock.有工作吗?
客户端:
fetch('/foo') //hostname: http://localhost:8080
.then(res => res.json())
.then(data => console.log(data))
.catch(e => console.log(e))
Run Code Online (Sandbox Code Playgroud)
测试套件
nock('/')
.get('/foo')
.reply(200, {data: "hello"})
Run Code Online (Sandbox Code Playgroud)
这是失败的,因为我没有给出正确的主机名nock.难道我做错了什么?
在node.js中,我很难让superagent和nock一起工作.如果我使用请求而不是superagent,它可以完美地运行.
以下是superagent无法报告模拟数据的简单示例:
var agent = require('superagent');
var nock = require('nock');
nock('http://thefabric.com')
.get('/testapi.html')
.reply(200, {yes: 'it works !'});
agent
.get('http://thefabric.com/testapi.html')
.end(function(res){
console.log(res.text);
});
Run Code Online (Sandbox Code Playgroud)
res对象没有'text'属性.有些不对劲.
现在,如果我使用请求做同样的事情:
var request = require('request');
var nock = require('nock');
nock('http://thefabric.com')
.get('/testapi.html')
.reply(200, {yes: 'it works !'});
request('http://thefabric.com/testapi.html', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
})
Run Code Online (Sandbox Code Playgroud)
模拟的内容正确显示.
我们在测试中使用了superagent,所以我宁愿坚持下去.有谁知道如何使它工作?
谢谢你,Xavier
你好在redux文档中进行测试,他们有这个例子来测试api调用:
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../../actions/counter'
import * as types from '../../constants/ActionTypes'
import nock from 'nock'
const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
describe('async actions', () => {
afterEach(() => {
nock.cleanAll()
})
it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => {
nock('http://example.com/')
.get('/todos')
.reply(200, { body: { todos: ['do something'] }})
const expectedActions = [
{ type: types.FETCH_TODOS_REQUEST },
{ type: types.FETCH_TODOS_SUCCESS, body: { todos: …Run Code Online (Sandbox Code Playgroud) 我正在学习如何测试并使用一些示例作为指导我试图模拟登录帖子.该示例使用了对http调用的提取,但我使用的是axios.这是我得到的错误
超时 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时内未调用异步回调
这个错误的所有答案都与fetch有关,我如何用axios做到这一点
./saga
const encoder = credentials => Object.keys(credentials).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(credentials[key])}`).join('&')
const postLogin = credentials => {
credentials.grant_type = 'password'
const payload = {
method: 'post',
headers: config.LOGIN_HEADERS,
data: encoder(credentials),
url: `${config.IDENTITY_URL}/Token`
}
return axios(payload)
}
function * loginRequest (action) {
try {
const res = yield call(postLogin, action.credentials)
utils.storeSessionData(res.data)
yield put({ type: types.LOGIN_SUCCESS, data: res.data })
} catch (err) {
yield put({ type: types.LOGIN_FAILURE, err })
}
}
function * loginSaga () {
yield takeLatest(types.LOGIN_REQUEST, loginRequest) …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用karma服务器和nock创建一些基本测试.似乎nock根本没有拦截我的请求,有没有人有想法?我无法弄清楚遗漏了什么.我仍然得到真实的数据.
nock('https://api.github.com/users/' + username).log(console.log)
.get('/')
.query(true)
.reply(400, {
statusMessage: 'Bad Request',
foo: 'foo'
})
http.get('https://api.github.com/users/' + username, function(res) {
console.log('res', res)
})
Run Code Online (Sandbox Code Playgroud)
我还添加了这个中间件
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
Run Code Online (Sandbox Code Playgroud)
======更新6月6日======
使用react-redux的整个流程这是我的测试:
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import axios from 'axios';
import expect from 'expect';
import * as actions from 'actions/test-actions'
import * as types from 'types';
import nock from 'nock'
import { username } from 'constansts'
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('Asynchronous …Run Code Online (Sandbox Code Playgroud) 我正在尝试在redux应用程序中测试api调用.代码几乎遵循redux文档的Async Action Creators部分中概述的模式:
http://redux.js.org/docs/recipes/WritingTests.html
它的要点是你使用redux-mock-store来记录和断言任何被触发的动作.
这是整个测试,使用nock来模拟api调用:
import React from 'React'
import ReactDOM from 'react-dom'
import expect from 'expect';
import expectJSX from 'expect-jsx';
import TestUtils from 'react-addons-test-utils'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import nock from 'nock'
expect.extend(expectJSX);
import * as types from '../../constants/Actions'
describe('Async Search Actions', () => {
const thunkMiddleware = [ thunk ];
/* use redux-mock-store here */
const mockStore = configureMockStore(thunkMiddleware);
describe('The fetchArtistData action creator should', () => {
afterEach(() => …Run Code Online (Sandbox Code Playgroud) 我正在构建一个带有服务器端渲染 (SSR) 的单页 Web 应用程序 (SPA)。
我们有一个节点后端 API,它在 SSR 期间从节点服务器调用,在初始渲染后从浏览器调用。
我想编写 e2e 测试来配置 API 响应(如 with nock)并同时处理浏览器调用和 SSR 服务器调用。一些伪代码:
it('loads some page (SSR mode)', () => {
mockAPI.response('/some-path', {text: "some text"}); // here i configure the mock server response
browser.load('/some-other-page'); // hit server for SSR response
expect(myPage).toContain('some text');
})
it('loads some other page (SPA mode)', () => {
mockAPI.response('/some-path', {text: "some other text"}); // here i configure another response for the same call
browser.click('#some-link'); // loads another page client …Run Code Online (Sandbox Code Playgroud) 我正在将 Nock 与 Mocha 一起使用,并想检查请求中是否存在某些标头。我不关心其他标头,也不关心我正在检查其存在的标头的具体内容。是否有捷径可寻?.matchHeader()当特定标头不存在时通过,reqheaders除非我指定所有标头字段,否则失败。
nock ×10
node.js ×7
javascript ×3
reactjs ×2
redux ×2
testing ×2
chai ×1
cypress ×1
fetch ×1
jestjs ×1
karma-mocha ×1
karma-runner ×1
mocha.js ×1
request ×1
sinon ×1
superagent ×1
tdd ×1