Code Monkey home page Code Monkey logo

superagent-mocker's People

Contributors

a avatar evanboho avatar ikhilko avatar j0hnsmith avatar kilahm avatar kmudrick avatar kornelski avatar leopoldofu avatar maxkoryukov avatar serga-kiev avatar tbranyen avatar yalishizhude avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

superagent-mocker's Issues

Maybe it's a bug~

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

Mocking an error response

I'm trying to mock a POST call that would return a 401 Unauthorized error for some testing. Any way to do this?

Incorrect mocking of `req.query`.

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:

  1. Write mock for a superagent request:
  mock.get(...api-address..., (req) => {
    console.log(req.query);
    return { status: 200 };
  });
  1. Write request and verify that { 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'] })
  1. Send the request to your server and log req.query, confirm it equals { baz: 'false', quux: ['a', 'b'] }.

Invalid status check

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

#9

New platform grahy dising

can't get query string

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?

Middlewares are not firing end/response triggers

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);
      }
    };

Confusing documentation

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()"

Cannot mock requests created with superagent constructor.

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,

MIT License

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?

Slowing down the response

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.

Aborting requests

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

Compatibility with superagent-bluebird-promise

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!

Request Headers are lowercased

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');
    });

});

Query with array parameters aren't captured correctly

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.

Double call callback

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

request.agent() is not patched

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;
  }

Types are not respected in the mock endpoint req.body

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.