|
| 1 | +const chai = require('chai'); |
| 2 | +const chaiHttp = require('chai-http'); |
| 3 | +const sinon = require('sinon'); |
| 4 | +const express = require('express'); |
| 5 | +const usersRouter = require('../../../src/service/routes/users'); |
| 6 | +const db = require('../../../src/db'); |
| 7 | + |
| 8 | +const { expect } = chai; |
| 9 | +chai.use(chaiHttp); |
| 10 | + |
| 11 | +describe('Users API', function () { |
| 12 | + let app; |
| 13 | + |
| 14 | + before(function () { |
| 15 | + app = express(); |
| 16 | + app.use(express.json()); |
| 17 | + app.use('/users', usersRouter); |
| 18 | + }); |
| 19 | + |
| 20 | + beforeEach(function () { |
| 21 | + sinon.stub(db, 'getUsers').resolves([ |
| 22 | + { |
| 23 | + username: 'alice', |
| 24 | + password: 'secret-hashed-password', |
| 25 | + email: 'alice@example.com', |
| 26 | + displayName: 'Alice Walker', |
| 27 | + }, |
| 28 | + ]); |
| 29 | + sinon |
| 30 | + .stub(db, 'findUser') |
| 31 | + .resolves({ username: 'bob', password: 'hidden', email: 'bob@example.com' }); |
| 32 | + }); |
| 33 | + |
| 34 | + afterEach(function () { |
| 35 | + sinon.restore(); |
| 36 | + }); |
| 37 | + |
| 38 | + it('GET /users only serializes public data needed for ui, not user secrets like password', async function () { |
| 39 | + const res = await chai.request(app).get('/users'); |
| 40 | + expect(res).to.have.status(200); |
| 41 | + expect(res.body).to.deep.equal([ |
| 42 | + { |
| 43 | + username: 'alice', |
| 44 | + displayName: 'Alice Walker', |
| 45 | + email: 'alice@example.com', |
| 46 | + title: '', |
| 47 | + gitAccount: '', |
| 48 | + admin: false, |
| 49 | + }, |
| 50 | + ]); |
| 51 | + }); |
| 52 | + |
| 53 | + it('GET /users/:id does not serialize password', async function () { |
| 54 | + const res = await chai.request(app).get('/users/bob'); |
| 55 | + expect(res).to.have.status(200); |
| 56 | + console.log(`Response body: ${res.body}`); |
| 57 | + |
| 58 | + expect(res.body).to.deep.equal({ |
| 59 | + username: 'bob', |
| 60 | + displayName: '', |
| 61 | + email: 'bob@example.com', |
| 62 | + title: '', |
| 63 | + gitAccount: '', |
| 64 | + admin: false, |
| 65 | + }); |
| 66 | + }); |
| 67 | +}); |
0 commit comments