2014-01-10 45 views
6

对于我的船帆的应用程序,我用下面的代码进行单元测试的用户模型,模型,但得到的错误消息:不能单元测试我在sailsjs

“类型错误:对象#有没有方法'创建”

var User = require('../../api/models/User'); 
var Sails = require('sails'); 

console.log(User); 

describe("User Model:", function() { 

    // create a variable to hold the instantiated sails server 
    var app; 

    // Global before hook 
    before(function(done) { 

    // Lift Sails and start the server 
    Sails.lift({ 

     log: { 
     level: 'error' 
     }, 

    }, function(err, sails) { 
     app = sails; 
     done(err, sails); 
    }); 
    }); 

    // Global after hook 
    after(function(done) { 
    app.lower(done); 
    }); 

    describe("Password encryption", function() { 

    describe("for a new user", function() { 
     var user; 
     before(function (cb) { 
     var userData = { 
      email: "[email protected]", 
      password: "test_password", 
      passwordConfirmation: "test_password" 
     }; 

     User.create(userData, function (err, newUser) { 
      if (err) return cb(err); 
      user = newUser; 
      cb(); 
     }); 
     }); 

     it("must encrypt the password", function() { 
     user.must.have.property('encryptedPassword'); 
     user.must.not.have.property('password'); 
     user.must.not.have.property('passwordConfirmation'); 
     }); 

     after(function (cb){ 
     user.destroy(function (err) { 
      cb(err); 
     }); 
     }); 
    }); 

在我看来,帆正确解除了,导致创建方法不可用的问题是什么?

+0

我对nodejs很陌生,试图为我正在构建的应用程序编写一些测试。是否有可能看看你的模型,以便我可以尝试弄清楚如何为我的模型编写测试。谢谢 – kushaldsouza

回答

14

删除第一行:

var User = require('../../api/models/User'); 

一旦帆的应用程序被提起,你都将自动获得你的模型,看到here,例如。

在你的情况中,你的第一行覆盖了由Sails.js构造的User模型,这就是为什么即使你有一个对象它不是水线模型。

+1

如果我在测试文件夹(任何文件夹下)下定义test.js文件,我就面临同样的问题。无法达到用户模型,显示错误“ReferenceError:用户未定义 ”。如果我写var User = require(' ../api/models/User.js');显示错误“类型错误:对象#没有方法'创建' ” – tajuddin

+0

@tajuddin请看[this example](https://github.com/bredikhin/sailsjs-mocha-testing-barrels-fixtures-example/blob /master/test/index.js)。 – bredikhin

+0

以上链接被破坏。 –