diff --git a/README.md b/README.md index ffcab92c..2fb881c9 100644 --- a/README.md +++ b/README.md @@ -10,3 +10,15 @@ Guided project for **Node Server Testing** Module. - [ ] type `npm run server` to start the API. Please follow along as the instructor adds automated tests to the API. + +## Testing an API + +- run the server on a port +- make an request to the endpoint (may or may not include data) +- inspect the result to the endpoint to see if it is what I expected + +- npm i supertest jest +- add test script : "test": "jest --watch" +- add environment : "jest":{ "testEnvironment":"node"} + +Jest will default to running code in an environment similar to a web browser. For testing node servers, we need to change that option diff --git a/api/server.js b/api/server.js index 52c80536..27619496 100644 --- a/api/server.js +++ b/api/server.js @@ -10,6 +10,10 @@ server.get("/", (req, res) => { res.status(200).json({ api: "up" }); }); +// returns http 200 +// returns json +// the body has an api property and the values is up + server.get("/hobbits", (req, res) => { Hobbits.getAll() .then(hobbits => { diff --git a/api/server.spec.js b/api/server.spec.js new file mode 100644 index 00000000..0845aaba --- /dev/null +++ b/api/server.spec.js @@ -0,0 +1,27 @@ +const supertest = require('supertest') +const { intersect } = require('../data/dbConfig') +const server = require('./server') + + +describe('server', () => { + describe('GET', () => { + it ("should return 200", () => { + return supertest(server).get('/').then (res=> {expect(res.status).toBe(200)}) + }) + // it('should have a body', () => { + // return supertest(server).get('/').then(res => {expect(res.body).toEqual({api:"up"})} ) + // }) + it('should have a body api:up', () => { + return supertest(server).get('/').then(res => {expect(res.body.api).toBe("up")} ) + }) + + it("should return JSON", () => { + return supertest(server) + .get("/") + .then(res => { + expect(res.type).toMatch(/json/i); + }); + }); + + }) +}) \ No newline at end of file diff --git a/index.js b/index.js index c01aa681..253ac6d4 100644 --- a/index.js +++ b/index.js @@ -2,5 +2,7 @@ require('dotenv').config(); const server = require('./api/server.js'); + + const port = process.env.PORT || 5000; server.listen(port, () => console.log(`\n** server up on port ${port} **\n`)); diff --git a/package.json b/package.json index 0d9f56bd..2bd157f4 100644 --- a/package.json +++ b/package.json @@ -5,17 +5,24 @@ "main": "index.js", "scripts": { "server": "nodemon index.js", - "start": "node index.js" + "start": "node index.js", + "test": "jest --watch" }, "keywords": [], "author": "Lambda School", "dependencies": { "dotenv": "^8.2.0", "express": "^4.17.1", + "jest": "^26.5.3", "knex": "^0.21.6", - "sqlite3": "^5.0.0" + "pg": "^8.4.1", + "sqlite3": "^5.0.0", + "supertest": "^5.0.0" }, "devDependencies": { "nodemon": "^2.0.5" + }, + "jest": { + "testEnvironment": "node" } }