简体   繁体   中英

Error unit tests using (mocha , chai) in nodejs

I have an error when I run a test: mocha test.js .

This is the error :

const chaiHttp = require('chai-http');
const sinon = require('sinon');
const sinontest = require('sinon-test');
const test = sinontest(sinon);
const chai = require('chai');
const accounts_controller = require('../controllers/accountsController');
const tickets_controller = require('../controllers/ticketsController');
const gains_controller = require('../controllers/gainsController');
const config = require('./config');
const router = config.serverdev;
const { expect } = chai;
const accounts_spec = require('./accountsSpec'); 

//configuration of chai
chai.use(chaiHttp);
chai.should();

Account
   create an admin account
     Should create a new admin account:
 Uncaught TypeError: Cannot read property 'should' of undefined
  at /api/test/accountsSpec.js:41:17
  at Test.Request.callback (node_modules/superagent/lib/node/index.js:728:3)
  at ClientRequest.<anonymous> (node_modules/superagent/lib/node/index.js:647:10)
  at TLSSocket.socketErrorListener (_http_client.js:432:9)
  at errorOrDestroy (internal/streams/destroy.js:128:12)
  at onwriteError (_stream_writable.js:463:3)
  at onwrite (_stream_writable.js:484:7)
  at internal/streams/destroy.js:60:7
  at TLSSocket.Socket._destroy (net.js:673:5)
  at TLSSocket.destroy (internal/streams/destroy.js:55:8)
  at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:93:12)

and this is my code :

describe('Account', () => {
/* 
* create admin account group description
*/
describe('create an admin account', () => {
    /* 
    * test case to check if addadmintestaccount function exist 
    */
    it('Should exist',test(function(){
        expect(accounts_controller.addadmintestaccount).to.not.be.undefined;
    }));
    /* 
    * test case to create a new admin account
    */
    it('Should create a new admin account',(done) => {
        chai.request(router)
        .post('/api/test/addadmintestaccount')
        .set("Content-Type", "application/json")
        .end((err,res)=>{
        res.should.have.status(200);
        expect(res.body.success).to.equals(true);
        adminToken = res.body.result;
        exports.adminToken = adminToken;
        done();
        });
    });
});
});

You must use chai-http plugin and call chai.should :

let chaiHttp = require('chai-http');

let should = chai.should();

chai.use(chaiHttp);

Second, your error is Cannot read property 'should' of undefined so res is undefined . Please check you create success post(without err )

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