2017-03-27 14 views
0

我想单元测试我的代码。 我有这样的事情:如何重新调整Nodejs的单元测试问题?

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

==>运行测试

所以我的问题是我期待res.send('title is required’);火和代码将停止处理查询时输出TypeError: Cannot read property 'then' of undefined。但由于某种原因,myModel.create()仍然火灾。我是这个框架的新手,并不确定哪里出了问题。有人可以帮助我吗?非常感谢!

+1

是不是可以声明var'model',而在之后使用对象'models'?你的'myModel.create'方法返回一个可靠的吗? – amenadiel

+0

当你从'testController'返回'create'时会发生什么? – Pytth

+0

@amenadiel好抓,但这只是我的错字。 – Jwqq

回答

1

看起来你只需要从testController返回create

+0

谢谢,但它仍然有相同的错误。 – Jwqq

+0

如果你这样做了,那么你还需要将'testObj.create(test_req,test_res);'更改为'testObj(test_req,test_res);' – Pytth

+0

我对我的问题采用了解决方法。谢谢您的帮助。 +1 – Jwqq