Jwqq
Jwqq

Reputation: 1087

How to reslve my unit test issue for Nodejs?

I am trying to unit test my codes. I have something like this:

testController.js

var testController = function(){
    var create = function(req, res) {
        var params = req.body;

        if (!params.title) {
            res.status(400)
            res.send('title is required’);
        }

        //proceed if title is passed
        myModel.create({
            'title': params.title,
        }).then(function(data){
            res.json(data);
        }).catch(function(err){
            res.json(err);
        })
    }
})

testController.spec.js

var sinon = require('sinon'),
    should = require('should’);

describe(‘my test', function(){
    beforeEach(function() {
        testCtrl = require('../controllers/testController');
        models = require('../models');
        myModel = models.myModel;
        testObj = new testCtrl();
    });

    describe(‘my test 1’, function(){
        it('should return 400 if missing title’, function() {
            //no title
            var test_req = {
               'body' : {}
            };
            var test_res = {
                'status': function(){},
                'send':function(){},
                'json':{
                    "test":"test"
                }
            };

            var stub = sinon.stub(myModel, 'create');

            testObj.create(test_req, test_res);

            stub.restore();
        })
    })
})

==> output TypeError: Cannot read property 'then' of undefined when run the test

So My issue is I am expecting res.send('title is required’); to fire and the code will stop processing the query. But for some reason, the myModel.create() still fires. I am new to this framework and not sure what is wrong. Can someone helps me about it? Thanks a lot!     

Upvotes: 0

Views: 97

Answers (1)

Pytth
Pytth

Reputation: 4176

Looks like you just need to return create from your testController.

Upvotes: 1

Related Questions