添加mongoose

  1. mkdir models
  2. npm i -S mongoose
  3. npm i -S mongoosedao

在路由里增加创建代码

配置

配置mongodb链接信息

  • config/mongodb.example.js
  • db.js
  1. cp config/mongodb.example.js config/mongodb.js

创建models/user.js

  1. var mongoose = require('mongoose');
  2. var Schema = mongoose.Schema;
  3. var MongooseDao = require('mongoosedao');
  4. var userSchema = new Schema(
  5. {
  6. "name":"String",
  7. "password":"String"
  8. }
  9. );
  10. var User = mongoose.model('User', userSchema);
  11. var UserDao = new MongooseDao(User);
  12. module.exports = UserDao;

测试user.js

  1. var request = require('supertest');
  2. var assert = require('chai').assert;
  3. var expect = require('chai').expect;
  4. require('chai').should();
  5. require('../db')
  6. var User = require('../models/user')
  7. // 测试代码基本结构
  8. describe('UserModel', function(){
  9. before(function() {
  10. // runs before all tests in this block
  11. })
  12. after(function(){
  13. // runs after all tests in this block
  14. })
  15. beforeEach(function(){
  16. // runs before each test in this block
  17. })
  18. afterEach(function(){
  19. // runs after each test in this block
  20. })
  21. describe('#save()', function(){
  22. it('should return stuq when user save', function(done){
  23. User.create({"name":"stuq","password":"password"},function(err, user){
  24. if(err){
  25. expect(err).to.be.not.null;
  26. done();
  27. }
  28. expect(user.name).to.be.a('string');
  29. expect(user.name).to.equal('stuq');
  30. done();
  31. });
  32. })
  33. })
  34. })

在测试完成后需要在after里删除测试数据,保证测试完整性,自己写吧

在路由里增加user创建和api测试

routes/user.js

  1. var User = require('../models/user')
  2. router.post('/register', function(req, res, next) {
  3. var name = req.body.name;
  4. var password = req.body.password;
  5. User.create({
  6. "name":name,
  7. "password":password
  8. },function(err, user){
  9. if(err){
  10. res.json('register failed with err');
  11. }
  12. res.json('register sucess');
  13. });
  14. });

test/user_api.js

  1. var request = require('supertest');
  2. var assert = require('chai').assert;
  3. var expect = require('chai').expect;
  4. require('chai').should();
  5. var app = require('../app');
  6. require('../db')
  7. describe('POST /users/register', function(){
  8. it('respond register with json', function(done){
  9. request(app)
  10. .post('/users/register')
  11. .field('name', 'stuq')
  12. .field('password', '123456')
  13. .set('Accept', 'application/json')
  14. .expect('Content-Type', /json/)
  15. .expect(200, done);
  16. })
  17. })

测试

  1. mocha -u bdd test/user_api.js