pretenderjs / pretender Goto Github PK
View Code? Open in Web Editor NEWA mock server library with a nice routing DSL
License: MIT License
A mock server library with a nice routing DSL
License: MIT License
I just tried pretender with the jspm package manager, but there are some internals it tries that defeats jspm, in particular this line:
var FakeXMLHttpRequest = isNode ? require('./bower_components/FakeXMLHttpRequest/fake_xml_http_request') : window.FakeXMLHttpRequest;
in a jspm environment pretender thinks it's in node, but then tries to do a require directly from a bower_components
directory which isn't there in a jspm setup. Since jspm is actually not in node the whole detection of node might also be somewhat fragile.
Since we're mocking the XHR object, we don't see requests in the Network tab of the dev tools.
Would you be open to a PR adding options to the Pretender
constructor that allowed passing in a namespace
, similar to Ember Data's namespace property?
Example usage:
server = new Pretender(function(){
this.get('users/:user_id', function() { ... });
}, {namespace: 'api/v1'});
This will intercept a GET request to /api/v1/users/:user_id
.
To reproduce:
0.7.0
)node_modules
and bower_components
, and npm i; bower i
if you likenpm test
I'm using
var server = new Pretender(function(){
this.post('/ubus', this.passthrough);
});
This changes the requests' Content-Type
header from
Content-Type:application/json
to
Content-Type:text/plain;charset=UTF-8
so that I get a 500 error back from the server.
I have a similar question to this issue but not for Ember, just for a simple project not using any MVC framework.
Using Karma, Mocha, and RequireJS, where would the pretender server code go? And does it need to run beforeEach test or should it only run once at the beginning of the test suite?
Just thought of doing this through pretender in one of my projects and was wondering if anyone had experience?
https://github.com/trek/pretender/blob/master/pretender.js#L36-L50
adding this.alive = true
here https://github.com/trek/pretender/blob/master/pretender.js#L33
adding this.alive = false
here https://github.com/trek/pretender/blob/master/pretender.js#L136
and checking pretender.alive
here https://github.com/trek/pretender/blob/master/pretender.js#L44 will allow pretender to assert.
How can this happen?
var server = new Pretender();
var myRequest = new XMLHttpRequest();
// setup stuff
// some async
setTimeout(function(){
myRequest.send();
}, 0);
server.shutdown();
sync case.
var server = new Pretender();
var myRequest = new XMLHttpRequest();
// setup stuff
// some async
server.shutdown();
myRequest.send();
This may be intentional, though I don't understand why: the latest release on npm is behind the latest release on github.
I know this seems simplistic but I don't see in the README where we are supposed to put our mock server code. Basically, where do we put the code below in an Ember-cli app?
var PHOTOS = {
"10": {
id: 10,
src: 'http://media.giphy.com/media/UdqUo8xvEcvgA/giphy.gif'
},
"42": {
id: 42,
src: 'http://media0.giphy.com/media/Ko2pyD26RdYRi/giphy.gif'
}
};
var server = new Pretender(function(){
this.get('/photos', function(request){
var all = JSON.stringify(Object.keys(PHOTOS).map(function(k){return PHOTOS[k]}))
return [200, {"Content-Type": "application/json"}, all]
});
this.get('/photos/:id', function(request){
return [200, {"Content-Type": "application/json"}, JSON.stringify(PHOTOS[request.params.id])]
});
});
Is there a reason that the bower install needs to be run on postinstall? It requires bower to be installed for projects using pretender as an npm dependency.
"scripts": {
"postinstall": "bower install"
}
I'd like to not have to JSON.stringify({}) all the time.
Currently it is not possible to register handlers for URLs, only paths. When looking for a handler for the upcoming request, Pretender checks if the first char of the path is a '/', and if not, adds the slash.
Thus a handler registered for e.g http://api.twitter.com will never be "recognized". I think the reason is probably using the RouteRecognizer for finding the handler so I'm not sure if this could be remedied but I think it's a common enough use case to see what can be done about it or how others dealt with this.
I ended up transforming the URL for the request only in testing (so e.g https://api.twitter.com/endpoint would become /twitter-api/endpoint) so that I could stub it out with Pretender. Not a big fan of this, though, since I had to add non-testing code to facilitate testing.
Currently, there doesn't seem to be a way to only use Pretender for only a couple of specific paths, while allowing everything else to behave normally.
I'm trying to use Pretender to stub out data for one or two endpoints that aren't built out yet on the server. Since I do have a whole lot of other endpoints that are built out, I'd like to tell it to go ahead and treat all unhandled requests as passthroughs. Essentially, if I didn't tell it what to do for a path, let my server handle it.
Ideally, we'd like to have new Pretender instances be created from existing instances. This would allow you to re-use a set of routes in tests. I think this would be especially useful for nested tests. You can get this behavior today by sharing route maps, but it's a little manual and limited to a depth of 1.
This will likely require pretty major internal refactoring?
When running
npm install prentender
as root user, bower fails as the --allow-root
option isnt set.
We ran into this issue on Docker, where running commands as the root user is the norm.
Is it possible in pretender to create a route that returns a promise? I have a need to communicate via postMessage to a parent window before I can return the correct response. Is there any built in way to respond to a request asynchronously?
Hello,
sometimes urls requests are performed by 3rd party libraries and they use an absolute url, like http://localhost:4200/api/v1/s3_mock
, when initial path was only /api/v1/s3_mock
.
For that case it will be good to have some request pre-processing hook(s), which will allow altering request url, something analogues to the server.prepareBody
and server.prepareHeaders
hooks.
Ran into an interesting thing today where I simulated a 302 response from an API using pretender and TDD'd some app functionality. However, when I integrated the actual API, I found that the 302 was never seen by jQuery, leading my feature to be broken with the real API despite working with pretender.
After some research, it turns out that part of the XMLHttpRequest spec says that redirects should be followed, transparently to the client:
If the origin of the URL conveyed by the Location header is same origin
with the XMLHttpRequest origin and the redirect does not violate infinite
loop precautions, transparently follow the redirect while observing the
same-origin request event rules.
Ideally, pretender would exhibit this behavior, too.
Is there any way to stub cross-domain XHR requests?
I'm wondering if it's possible to dynamically register request handlers at time of request, i.e. look up a handler when the actual request is made. I'd like to do this so that my addon can respond to requests by looking up a handler if it exists at, say, /app/pretender/routes/some-route.js
.
Is this possible now? I was thinking about doing it in the unhandledRequest
, but I'm not sure I can invoke handleRequest
from there? Any suggestions about how to approach this/work a possible PR?
// trigger the route map DSL.
for(i=0; i < arguments.length; i++){
this.map(arguments[i]);
}
Is there a reason why the counter is added to the window object?
It would be nice to be able to use fetch
instead of XMLHttpRequest
. When using the non-native fetch
polyfil Pretender would likely still work (because the polyfill uses XMLHttpRequest
to implement fetch
), but it doesn't seem that native fetch requests would be handled by Pretender.
Spec: https://fetch.spec.whatwg.org
This issue is mostly to lay out a path forward.
it would be very handy to have some sort of filtering functionality where a function would be executed before a request handler and if that function returned a value, that value should be sent back as the request response.
server.post('api/orderhistory',{ before: 'authFilter' } , function(request){
var ORDERS = some data;
return [200, "Content-Type": "application/json" , ORDERS];
});
server.filter('authFilter', function( request) {
//chech request headers to see if access token exists otherwise return
return [403,{"Content-Type": "application/json"},JSON.stringify({status:'failed',message:'access denied'})];
});
this way you can define a filter once and enforce it on multiple routes. the key is treating a possible response from the filter as response for the request.
So consumers of the app have a better idea of what's changed between versions.
This could make for some great isomorphism :-)
Example:
var server = new Pretender();
server.put('/api/songs/99', function(request) {
return new Promise(function(resolve, reject) {
resolve([404, {}, ""]);
});
});
pretender intercepts my requests successfully, but no matter what I do, pretender won't recognize my requests, and when I log the pretender object, my requests go to unhandled, my handler is in the handlers array, but in that object, there is no real indication in that object of what the handler is set to handle
i have no way of troubleshooting...
my current set up is this:
export default Ember.Route.extend({
beforeModel: function() {
server = new Pretender(function() {
console.log('this part runs');
this.get('/node/api/inbox', function(request) {
console.log('y u no run', request);
return [200, {"Content-Type": "application/json"}, messages];
});
});
console.log(server);
},
model: function() {
console.log(this.store.find('inbox'));
// return this.store.find('inbox');
},
afterModel: function() {
server.shutdown();
}
});
and it tells me:
Pretender intercepted GET http://mydomain/node/api/inbox but no handler was defined for this type of request
(real domain not shown to not expose it publicly)
Failing test:
test("can register queryParam urls", function(){
var queryCalled = false;
var noQueryCalled = false;
pretender.get('/some/path?a=1&b=2', function(request){
queryCalled = true;
});
pretender.get('/some/path', function(request){
noQueryCalled = true;
});
$.ajax({url: '/some/path?a=1&b=2'});
ok(!noQueryCalled, 'should be false');
ok(queryCalled, 'should be true');
});
I have tracked the problem down to RouteRecognizer: https://github.com/tildeio/route-recognizer/blob/master/lib/route-recognizer.js#L475-L523
It appears that RotueRecognizer will register the original path along with the queryParams. However in the linked function above the queryParams are striped from the path and no handler is found for the truncated path.
My use-case is https://github.com/dockyard/ember-cli-proxy-fixtures. This module is recording request responses during the test suite for faster playback via Pretender on future runs.
Hi,
I am trying to POST to a complete url that is registered in pretender.
POST http://yyy-api.xxx.local:6200/something/v1/cake
I can register a simple get request "/fish" but when I try to register 'http://moo.local/fish"
I don't get a match.
What would it take to support full URLs?
Currently, the following does not throw an error:
pretender.get('some-url', someVarThatIsActuallyUndefinedByMistakeBecauseItsMisspelleeeed);
According to the XHR2 specification (https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#make-progress-notifications):
while the download is progressing, queue a task to fire a progress event named progress about every 50ms or for every byte received, whichever is least frequent.
How do you feel about pretender triggering that event each 50ms by default? If nobody is listening, it's ok. Alternatively you can trigger only if there is an "onprogress" handler attached to the relevan object.
We use pretender to stub an Ember application, we have some sounds that are loaded and played while using the application. Loading and playing sounds fails because the pretender doesn't handle the xhr.responseType. We use Howler to load and play sounds, Howler sets the xhr.responseType to 'arraybuffer'. Pretender doesn't handle 'arraybuffer' which results in an error because Howler expects an arraybuffer. I've been trying all day to fix this in Pretender but without success so far.
This is how Howler loads an audiofile
https://github.com/goldfire/howler.js/blob/master/howler.js#L1230
I would also like to be able to access the headers and get to the authorization bearer token for simulating oauth, how can I get to these fields in the request
object?
Currently responses occur synchronously. This can create subtle self-trolls where your code assumes responses will occur immediately in testing but the don't in production.
How can I access the data passed via a post request?
Based on the evil trout video on pretender I'd like to do something like this:
this.post('/api/v1/token', function(request){
console.log(request);
var data = parsePostData(request.requestBody); // doesn't work
// check username and password and if okay
var response = {
"access_token": "myaccesstoken==",
"token_type": "bearer"
};
return [200, {}, response];
Seems NPM still things you're asking for route-recognizer 0.1.1?
$ npm install pretender
npm http GET https://registry.npmjs.org/pretender
npm http 304 https://registry.npmjs.org/pretender
npm http GET https://registry.npmjs.org/fake-xml-http-request
npm http GET https://registry.npmjs.org/route-recognizer
npm http 304 https://registry.npmjs.org/fake-xml-http-request
npm http 304 https://registry.npmjs.org/route-recognizer
npm ERR! notarget No compatible version found: route-recognizer@'>=0.1.1-0 <0.2.0-0'
npm ERR! notarget Valid install targets:
npm ERR! notarget ["0.1.0"]
npm ERR! notarget
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
I get the following error whenever i run 'npm install'. Looks like bower dependency was not installed before running the postinstall step?
npm install
npm WARN package.json [email protected] assert is also the name of a node core module.
|
[email protected] postinstall /Users/jlidder/Documents/repos/temp3/fba/node_modules/pretender
bower install
sh: bower: command not found
npm ERR! Darwin 13.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install"
npm ERR! node v0.12.0
npm ERR! npm v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] postinstall: bower install
npm ERR! Exit status 127
npm ERR!
npm ERR! Failed at the [email protected] postinstall script 'bower install'.
npm ERR! This is most likely a problem with the pretender package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! bower install
npm ERR! You can get their info via:
npm ERR! npm owner ls pretender
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/jlidder/Documents/repos/temp3/wtvproject/npm-debug.log
Move Pretender (and all its dependencies) to ES6 style modules.
Tests:
Publish:
Hi, I'm trying to use Pretender to mock my server requests, but I always get this error:
Setup failed on something: undefined is not a function
at Object.Pretender (http://localhost:9876/base/app/assets/vendor/components/pretender/pretender.js:12:10)
at Object.singleModule.setup (http://localhost:9876/base/tests/specs/integration/a_routes_test.js:4:24)
at Object.Test.setup (http://localhost:9876/base/node_modules/qunitjs/qunit/qunit.js:1276:31)
at http://localhost:9876/base/node_modules/qunitjs/qunit/qunit.js:1460:10
at process (http://localhost:9876/base/node_modules/qunitjs/qunit/qunit.js:1016:24)
at http://localhost:9876/base/node_modules/qunitjs/qunit/qunit.js:186:5
debug.html:31window.__karma__.result debug.html:31(anonymous function) adapter.js:66runLoggingCallbacks qunit.js:1167Test.finish qunit.js:1434(anonymous function) qunit.js:1469process qunit.js:1016(anonymous function)
After trying with my specific tests, I've tryed to do a simple test to reproduce this so I have this code:
(code in coffeescript)
singleModule "Posts",
setup: ->
pretender = new Pretender () ->
@get "/posts", (request) ->
[
200
{
"Content-Type": "application/json"
}
]
return
test "something", ->
$.get "/posts", (data) ->
console.log data
The problem comes from inside of pretender.js in Pretender(maps) function,
the maps.call(this); or maps() is always returning undefined.
Do someone have a idea of what could be happening here?
Best Regards,
Marius
When trying to use Pretender in my tests, I keep getting an error that a PUT
request is being unhandled.
"Pretender intercepted PUT http://api.lvh.me:3000/passwords/4615efd359fb8d96804a1d77efea78e528667d62
but no handler was defined for this type of request"
But from the test below, it seems to be pretty clearly handled.
`import { test, moduleFor } from 'ember-qunit'`
`import startApp from '../helpers/start-app'`
App = undefined
server = undefined
module "Integration: Reset Password",
setup: ->
App = startApp()
response =
user:
email: "[email protected]"
server = new Pretender(->
@put "/passwords/4615efd359fb8d96804a1d77efea78e528667d62", (request)->
return [201, {"Content-Type": "application/json"}, JSON.stringify(response)]
)
teardown: ->
Ember.run App, App.destroy
server.shutdown()
test "Resets the password", ->
expect 1
visit("/passwords/4615efd359fb8d96804a1d77efea78e528667d62").then ->
fillIn "#password", "newpassword"
click("form button").then ->
equal find(".alert-success p").text(), "You can now login with your new password.", "The password reset success notice renders"
I'm expecting this is a user error, but I'm really stumped at the moment.
I can't get passthrough to work with jQuery 1.x. The requests are sent using $.ajax('/path').then(...)
but the then
callbacks are never fired.
Seems like the onload
event is detected on the browser xhr
but is not supported by the 1.x jQuery xhr
module, so it is not dispatched when the response is received.
I was able to get the events to fire by removing the check for onload
and just adding both events.
There is a chance that both events could be fired I'm guessing. Any other concerns I should check into before getting a PR ready?
Could you publish to npm? pretender
package name is still available.
Is there any way to get/log the response data in handledRequest
, or some other callback? I'd like to log the verb/path + response each time one is made, similar to how the network tab shows actual XHR requests.
When working with routes (specifically passthrough) it would be helpful to have an all
route registration to allow handling of any HTTP verb.
For instance if an API has gone from needing mocks to needing passthrough, the code now becomes:
this.get('user', this.passthrough);
this.post('user', this.passthrough);
this.put('user', this.passthrough);
this.delete('user', this.passthrough);
Hello, there should be a way to interact with the 3rd party API, like S3 for example.
Right now even taking in account that passthrough is defined Pretender still throw an error:
this.post('https://bucket.s3.amazonaws.com', this.passthrough);
Error: Pretender will not respond to requests for URLs. It is not possible to accurately simluate the browser's CSP. Remove the https://bucket.s3.amazonaws.com from https://bucket.s3.amazonaws.com/ and try again
Is there any way to let Pretender know that for specified paths to continue using the actual request route? I would like to be able to fake out certain routes that are not handled by my application but have some go through to the real endpoints. I can't see an easy way to do this currently but I'm hoping you could point me in the right direction.
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.