a / superagent-mocker Goto Github PK
View Code? Open in Web Editor NEWPretty simple in-browser mocks for CRUD and REST API
Pretty simple in-browser mocks for CRUD and REST API
New platform grahy dising
A Data of unemployment rates in Ghana
between 2015 and 2020
I'm trying to mock a POST
call that would return a 401 Unauthorized
error for some testing. Any way to do this?
var obj = {id:1};
request.get('/a').query(obj).end();
In this situation,mock only has headers,body and cannot get the variable "obj",can support it?
Cannot mock requests sent this way.
superagent("POST", "/relative/url") .query() .send() .end()
mocking this is fine.
superagent.post("relative/url") .query() .send()
Is there a way to mock request on constructor at the moment ?
Thanks,
When superagent send two requests to one router path with diffrent request's body almost the same time.When the second request is sent while mock is dealing with the first request,the first request's body will be overwriten by the second request's body.
For instance.
mock.get('/test', function(req){
//logic code which costs CPU and long time
console.log(req.body);
//first request : {name:"b"}
//seconde request: {name:"b"}
});
superagent.get('/test').send({name:'a'});
superagent.get('/test').send({name:'b'});
I tried to sovle this problem and it works:
// setTimeout(function(s) {
try {
cb && cb(null, current(state.request));
} catch (ex) {
cb && cb(ex, null);
}
// }, value(mock.timeout), state);
I tried to fix it in this PR
#29
I am using .withCredentials() to send cookies (http://visionmedia.github.io/superagent/#cors) is this supported with superagent-mocker. If yes, can you provide me with an example for it ?
readme.md says to unmock with mock.unmock()
, actually it's mock.unmock(superagent)
.
Line 170 in bc51d1e
If I use superagent and set query to { foo: undefined, bar: [], baz: false, quux: ['a', 'b'] }
, superagent-mock generates a req.query object of { foo: 'undefined', bar: '', baz: 'false', quux: 'a,b' }
. However, in reality my api receives a query object of { baz: 'false', quux: ['a', 'b'] }
.
Steps to reproduce:
mock.get(...api-address..., (req) => {
console.log(req.query);
return { status: 200 };
});
{ foo: 'undefined', bar: '', baz: 'false', quux: 'a,b' }
is logged to console:request
.get(`...api-address...`)
.query({ foo: undefined, bar: [], baz: false, quux: ['a', 'b'] })
req.query
, confirm it equals { baz: 'false', quux: ['a', 'b'] }
.Does this lib allow you to mock abort requests?
I have code that allows users to abort their requests. When I swap in this lib in my tests, this lib errors:
Uncaught TypeError: Cannot read property 'aborted' of undefined
FYI, superagent now supports replacing superagent.Request
with another class, like this:
so you could use as an alternative way of patching it.
I'm using your library in conjunction with superagent-bluebird-promise
, but it seems not to work for non-200 responses.
The following superagent-bluebird-promise
code ends up causing an error:
Uncaught TypeError: Cannot read property 'status' of null
if (typeof res !== "undefined" && res.status >= 400) {
var msg = 'cannot ' + req.method + ' ' + req.url + ' (' + res.status + ')'
From: https://github.com/KyleAMathews/superagent-bluebird-promise/blob/master/index.js#L66-L67
This is happening when superagent-mocker
calls that function with res
passed in as null
rather than undefined
.
if (response.status !== 200) {
cb && cb(response, null);
From: https://github.com/A/superagent-mocker/blob/master/index.js#L99-L100
I'm not entirely sure which of your libraries is responsible for this bug, but either case looks like a pretty easy fix. (I've submitted an issue to superagent-mocker as well: KyleAMathews/superagent-bluebird-promise#53)
If you want, I can submit a PR to change
cb && cb(response, null);
to
cb && cb(response, undefined);
or
cb && cb(response);
Either change could be a quick fix for my issue.
Thanks for taking your time to contribute this very useful library to the OSS community!
This line confused me for quite a while: "You may set the body of a POST request as the second parameter of mock.post()". What this should say is: "you may set the mocked RESPONSE as the second parameter of mock.post()"
Status-Code: 201 (Created) should not throw an error but currently does, as just 200 is error free.
if (response.status !== 200) {
cb && cb(response, null);
} else {
cb && cb(null, response);
}
Also, Regarding #9
****
It's possible to make it work properly via subclassing — #44 — since the .agent()
method will invoke superagent.Request
.
A quick'n'dirty way of making it sort-of work (except cookies):
superagent.agent = function() {
return this;
}
If I mock an endpoint that takes an array of objects or string as a body param, when I get the body in the mock handler it is not what I am expecting. If I send an array I get a dictionary of the array in the body. If I send just a string, then I get nothing in the body param. Arrays and Strings are considered valid json and should be serialized and represented in the body parameter as they were passed in.
Here: https://github.com/A/superagent-mocker/blob/master/index.js#L98
Such code:
try {
// ...
// Code code code
// ...
// call 1
cb && cb(error, null);
} else {
cb && cb(null, response);
}
} catch (ex) {
// call 2
cb && cb(ex, null);
}
If you will try to use it with mocha
and expect
you will get callback doublecall, trying to assert in callback.
If this repo is alive - I could send a test case (not ready right now), and, probably, a PR
The headers in the request object passed into the callback for get
or post
mocks are getting lower-cased. While generally speaking, http headers are case-insensitive, it may actually matter for some http handling implementations.
import {default as request} from 'superagent';
import superagentMocker from 'superagent-mocker';
describe('making an api call', function() {
beforeEach(function(done) {
const mock = this.mock = superagentMocker(request);
const data = this.data = {
someDataProp: 'data!'
};
mock.get('/api/some-url', (req) => {
// req.headers keys are all lowercased. They should not be
this.request = req;
return {body: data};
});
const promise = getData();
promise.then(() => done()).catch(done);
});
it('should have correct headers', function() {
expect(this.request).to.have.deep.property('headers.Authorization', 'Bearer some token');
});
});
If I attach a middleware to mocked superagent - whether I try to substitute an end callback, or have a trigger on 'end', 'response' events - nothing works.
As soon as I unmock - everything works great.
MiddleWare example:
var middlewareSuperagent = function(req) {
console.log('STARTED');
req._callback_orig = req.callback;
req.callback = function(err, res) {
console.log('FINISHED');
req._callback_orig(err, res);
}
};
I'm looking at how we can simulate as much as possible what our real/production environment in offline development scenarios. Inline with this, we are fully faking out the server to be used during client dev work.
With this in mind, it would be nice if the api facilitated some way in which once could control when superagents end
callback gets called? In my case I would call it from within a setTimeout
.
for example, mock status code = 404
Based on http://visionmedia.github.io/superagent/#get-requests I'm providing it a string so i can use the format of string[]=one&string[]=two&string[]=three
, but when i check req.query
, it only shows it as req.query.string[]: three
.
Would it be possible to perhaps just be able to get the whole query as a string, to save you having to cater for all the possible variations? Even superagent doesn't support all the variations, thats why they have the 'supply as a string' option.
The terms of the MIT license indicate that the license itself must be distributed with any significant portions of the code. Unfortunately, I don't see a LICENSE
, LICENSE.txt
, LICENSE.md
nor any other source of the MIT license in your project.
Additionally, citing MIT © Shuvalov Anton
isn't quite the same as saying Copyright © 2016 Shuvalov Anton, Licensed under a MIT License
and the latter wording is significantly more correct.
I appreciate your work and I like that it seems that this library is being released under a MIT license, but currently it is legally ambiguous and that's potentially a hazard with using the tools. Would you be willing to add a file with the license or place the license at the top of your library?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.