Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ Assertion.prototype.set = function(name, value) {
return this;
}

Assertion.prototype.randomDelay = function(min, max) {
this.delay = 1;
this.minDelay = min;
this.maxDelay = max;
return this;
}

Assertion.prototype.delay = function(ms) {
this.delay = ms;
Expand All @@ -108,6 +114,9 @@ Assertion.prototype.reply = function(status, responseBody) {
var self = this;

this.app[this.method](this.path, function(req, res) {

self.request = req;

if(self.qs) {
assert.deepEqual(req.query, self.qs);
}
Expand All @@ -131,7 +140,11 @@ Assertion.prototype.reply = function(status, responseBody) {
res.status(status).send(responseBody);
};
if(self.delay) {
setTimeout(reply, self.delay);
var coef = 1;
if (self.minDelay && self.maxDelay) {
coef = Math.floor(Math.random() * (self.maxDelay - self.minDelay + 1)) + self.minDelay;
}
setTimeout(reply, self.delay * coef);
} else {
reply();
}
Expand Down Expand Up @@ -166,12 +179,11 @@ Handler.prototype.wait = function(ms, fn) {
fn = ms;
ms = this.defaults.waitTimeout;
}

var self = this;
var timeout = null;
var cb = function() {
clearTimeout(timeout);
fn();
fn(null, self.assertion.request);
}
this.once("done", cb);
timeout = setTimeout(function() {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "shmock",
"version": "0.7.1",
"version": "0.7.2",
"description": "Simple HTTP Mocking library",
"keywords": [
"express",
Expand Down
30 changes: 30 additions & 0 deletions test/shmock.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var supertest = require("supertest");
var shmock = require("..");
var should = require('should');

describe("shmock", function() {
it("Should be able to bind to a specific port", function(done) {
Expand Down Expand Up @@ -154,5 +155,34 @@ describe("shmock", function() {
});
});
});

it("Should be able to delay a reply for a random amount of ms", function(done) {
mock.get("/foo").randomDelay(30, 100).reply(200);

test.get("/foo").timeout(10).end(function(err) {
err.should.not.be.null;

test.get("/foo").timeout(120).expect(200, function(err) {
console.log(err);
(err == null).should.be.ok;

mock.get("/foobar").reply(200);
test.get("/foobar").timeout(10).expect(200, done);
});
});
});

it('Should forward the received request to the wait callback', function(done) {
var h = mock.post("/foo").reply(200);

h.defaults.waitTimeout = 10;

h.wait(function(err, req) {
req.body.x.should.be.equal(1);
done();
});

test.post("/foo").send({x: 1}).expect(200, function() {});
});
});
});