Skip to content

Commit

Permalink
Merge pull request #25 from loicsimon/master
Browse files Browse the repository at this point in the history
Add a cleanRequests() function to discard previous requests received by ServerMock
  • Loading branch information
teorossi82 authored Apr 1, 2020
2 parents d9869c6 + b61e258 commit fef2855
Show file tree
Hide file tree
Showing 4 changed files with 217 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.vscode
node_modules
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,20 @@ Returns the port at which the HTTP server is listening to or `null` otherwise. T

Returns the port at which the HTTPS server is listening to or `null` otherwise. This may be useful if you configure the HTTPS server port to `0` which means the operating system will assign an arbitrary unused port.

#### `reset()`

Clears request handlers and requests received by the HTTP server.

#### `resetHandlers()`

Clears all request handlers that were previously set using `on()` method.


#### `resetRequests()`

Clears all requests received by the HTTP server.



## Contribute

Expand Down
176 changes: 176 additions & 0 deletions spec/http_server_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,180 @@ describe("ServerMock", () => {
expect(res.statusCode).toBe(200);
});
});


describe("requests()", () => {
beforeEach(done => {
server = new ServerMock({ host: "localhost", port: 0 });
server.start(async () => {
server.on({
method: "PUT",
path: "/dog",
reply: {
status: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ breed: "German Shepherd" })
}
});
server.on({
method: "POST",
path: "/cat",
reply: {
status: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ breed: "Maine coon" })
}
});
server.on({
method: "DELETE",
path: "/bird",
reply: {
status: 204,
headers: { "content-type": "application/json" }
}
});

await client.request("localhost", server.getHttpPort(), "PUT", "/dog", { "Content-Type": "application/json" }, JSON.stringify({ breed: "German Shepherd" })).catch(error => console.error(error));
await client.request("localhost", server.getHttpPort(), "POST", "/cat", { "Content-Type": "application/json" }, JSON.stringify({ breed: "Maine coon" })).catch(error => console.error(error));
await client.request("localhost", server.getHttpPort(), "DELETE", "/bird").catch(error => console.error(error));

done();
});
});

it("should return all requests when given no arguments", async() => {
const requests = server.requests();

expect(requests).not.toBeNull();
expect(requests.length).toBe(3);
});

it("should return the request emitted on dog API when path equals 'dog'", () => {
const requests = server.requests({ path: '/dog' });

expect(requests).not.toBeNull();
expect(requests.length).toBe(1);
expect(requests[0].pathname).toBe('/dog');
expect(requests[0].method).toBe('PUT');
});

it("should return the request emitted on cat API when method equals 'POST'", () => {
const requests = server.requests({ method: 'POST' });

expect(requests).not.toBeNull();
expect(requests.length).toBe(1);
expect(requests[0].pathname).toBe('/cat');
expect(requests[0].method).toBe('POST');
});

it("should return the request emitted on bird API when method equals 'DELETE' and path equals 'bird'", () => {
const requests = server.requests({ path: '/bird', method: 'DELETE' });

expect(requests).not.toBeNull();
expect(requests.length).toBe(1);
expect(requests[0].pathname).toBe('/bird');
expect(requests[0].method).toBe('DELETE');
});
});

describe("reset()", () => {
beforeEach(done => {
server = new ServerMock({ host: "localhost", port: 0 });
server.start(async () => {
server.on({
method: "GET",
path: "/resource",
reply: {
status: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ hello: "world" })
}
});

await client.request("localhost", server.getHttpPort(), "GET", "/resource");

done();
});
});

it("should return only Not Found error after being invoked", async () => {
const res1 = await client.request("localhost", server.getHttpPort(), "GET", "/resource");
expect(res1.statusCode).toBe(200);

server.reset();

// As there isn't any handler anymore, returns a Not Found error.
const res2 = await client.request("localhost", server.getHttpPort(), "GET", "/resource");
expect(res2.statusCode).toBe(404);
});

it("should leave an empty requests array", () => {
server.reset();

const requests = server.requests();
expect(requests).not.toBeNull();

expect(requests.length).toBe(0, "Requests weren't cleaned");
});
});

describe("resetRequests()", () => {
beforeEach(done => {
server = new ServerMock({ host: "localhost", port: 0 });
server.start(async () => {
server.on({
method: "GET",
path: "/resource",
reply: {
status: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ hello: "world" })
}
});

await client.request("localhost", server.getHttpPort(), "GET", "/resource");

done();
});
});

it("should leave an empty requests array", () => {
server.resetRequests();

const requests = server.requests();
expect(requests).not.toBeNull();

expect(requests.length).toBe(0, "Requests weren't cleaned");
});
});

describe("resetHandlers()", () => {
beforeEach(done => {
server = new ServerMock({ host: "localhost", port: 0 });
server.start(() => {
server.on({
method: "GET",
path: "/resource",
reply: {
status: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ hello: "world" })
}
});

done();
});
});

it("should return only Not Found error after being invoked", async () => {
const res1 = await client.request("localhost", server.getHttpPort(), "GET", "/resource");
expect(res1.statusCode).toBe(200);

server.resetHandlers();

// As there isn't any handler anymore, returns a Not Found error.
const res2 = await client.request("localhost", server.getHttpPort(), "GET", "/resource");
expect(res2.statusCode).toBe(404);
});
});
});
33 changes: 32 additions & 1 deletion src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ function Server(host, port, key, cert)
address = null,
handlers = [],
requests = [],
connections = [];
connections = [],
self = this;

function _saveRequest(req, res, next) {
requests.push(req);
Expand Down Expand Up @@ -275,10 +276,28 @@ function Server(host, port, key, cert)
return this;
};

/**
* Clears request handlers and requests received by the HTTP server.
*/
this.reset = function() {
self.resetHandlers();
self.resetRequests();
}

/**
* Clears all request handlers that were previously set using `on()` method.
*/
this.resetHandlers = function() {
handlers = [];
};

/**
* Clears all requests received by the HTTP server.
*/
this.resetRequests = function() {
requests = [];
}

/**
* Returns an array containing all requests received. If `filter` is defined,
* filters the requests by:
Expand Down Expand Up @@ -325,7 +344,9 @@ function ServerVoid() {
this.requests = function() { return []; };
this.connections = function() { return []; };
this.getPort = function() { return null; };
this.reset = function() {};
this.resetHandlers = function() {};
this.resetRequests = function() {};
}

/**
Expand Down Expand Up @@ -374,10 +395,20 @@ function ServerMock(httpConfig, httpsConfig)
return httpsServerMock.getPort();
}

this.reset = function() {
httpServerMock.reset();
httpsServerMock.reset();
}

this.resetHandlers = function() {
httpServerMock.resetHandlers();
httpsServerMock.resetHandlers();
}

this.resetRequests = function() {
httpServerMock.resetRequests();
httpsServerMock.resetRequests();
}
}


Expand Down

0 comments on commit fef2855

Please sign in to comment.