简体   繁体   中英

How to carry unit test on router function NodeJS / Mocha / Chai

How should it seems, if I want carry unit tests on this router :

router
.post('/set-permission', (req, res) => {
    Board.updateBoard(req.body)
        .then(resp => { 
            console.log(resp.permissions);
            res.json(resp.permissions);
        })
})

module.exports = router;

I have folder in project/test inside is file .js with required chai library. Now I should execute this function with parameter? But how? Could someone explain me??

You can use chai.http for this, which allows you to test HTTP apps. Just make sure to export your app as you already do.

// api.spec.js
const chai = require('chai')
const chaiHttp = require('chai-http')
const server = require('../app.js')

chai.should()
chai.use(chaiHttp)

describe('User permissions', () => {
  it('sets the user permissions', () => {
    // Notice we are sending the request to the `server` export instead
    // of a URL
    return chai.request(server)
      .post('/set-permission')
      .then(res => {
        res.should.have.status(200)
        // add more tests here as you see fit
      })
      .catch(err => {
         throw err
      })
  })
})

Also note that this more of an integration test rather than a unit test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM