如何解决Nodejs的单元测试问题?

时间:2017-03-27 23:13:56

标签: node.js unit-testing mocha sinon

我正在尝试对我的代码进行单元测试。 我有这样的事情:

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();
        })
    })
})

==>运行测试时输出TypeError: Cannot read property 'then' of undefined

所以我的问题是我希望触发res.send('title is required’);,代码将停止处理查询。但出于某种原因,myModel.create()仍在激发。我是这个框架的新手,不知道出了什么问题。有人可以帮助我吗?非常感谢!     

1 个答案:

答案 0 :(得分:1)

您似乎只需要从create返回testController