精华 测试驱动来学习mongoose
发布于 9 年前 作者 i5ting 7849 次浏览 最后一次编辑是 8 年前 来自 分享

mongoose-test

this is a test example project for mongoose!

创建项目

express .

使用淘宝的npm源

nrm use taobao

安装依赖包

npm install

添加更多有用依赖

npm install --save mongoose
npm install --save bcrypt

安装服务器自动重载模块

npm install --save-dev supervisor

安装测试模块

mkdir test

npm install --save-dev mocha
npm install --save-dev chai
npm install --save-dev sinon
npm install --save-dev supertest
npm install --save-dev zombie

单元测试需要的各个模块说明

  • mocha(Mocha is a feature-rich JavaScript test framework running on node.js and the browser, making asynchronous testing simple and fun.)
  • chai(Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.)
  • sinon(Standalone test spies, stubs and mocks for JavaScript.)
  • zombie (页面事件模拟Zombie.js is a lightweight framework for testing client-side JavaScript code in a simulated environment. No browser required.)
  • supertest(接口测试 Super-agent driven library for testing node.js HTTP servers using a fluent API)

修改package.json

  "scripts": {
		"start": "./node_modules/.bin/supervisor ./bin/www",
  	"test": "./node_modules/.bin/mocha -u tdd"
	},

创建db/user_model.js

此文件里编写用户相关的mongodb操作

  • Schema define
  • virtual attr
  • save pre callback
  • UserSchema.methods
  • UserSchema.statics
  • findOne
  • user hash password with salt
  • getAuthenticated

创建test/user_model.js

测试2个方法

  • #save()
  • #getAuthenticated()

测试代码基本结构

describe('UserModel', function(){
	before(function() {
    // runs before all tests in this block
  })
  after(function(){
    // runs after all tests in this block
  })
  beforeEach(function(){
    // runs before each test in this block
  })
  afterEach(function(){
    // runs after each test in this block
  })
	
  describe('#save()', function(){
    it('should return sang_test2 when user save', function(done){
			。。。
    })
  })
})

生命周期说明

  • before
  • after
  • beforeEach
  • afterEach

断言

断言都是单元测试的核心

断言作为Assert类的静态方法。如果一个断言失败,方法的调用不会返回值,并且会报告一个错误。

如果一个测试包含多个断言,那些紧跟失败断言的断言都不会执行,因为此原因,通常每个测试方法最好只有一个断言。每个方法可以无消息调用,也可以是带有一个简单文本消息调用,或者带有一个消息以及参数调用。在最后一种情况下,使用了一个提供的文本以及参数来格式化消息。

目前流行的断言基本分为3类

  • assert风格
  • should风格
  • expect风格

没有好坏之分,只是看个人习惯

这里使用chai这个库,它支持3种风格的断言,非常方便

Chai has several interfaces that allow the developer to choose the most comfortable. The chain-capable BDD styles provide an expressive language & readable style, while the TDD assert style provides a more classical feel.

var assert = require('chai').assert;
var expect = require('chai').expect;
require('chai').should();

具体用法请查看http://chaijs.com/文档

测试命令

启动mongodb服务

mongod

服务器启动

npm start

测试

npm test

测试相关网址

更多

下面概念,请自行了解

  • TDD
  • BDD

代码: https://github.com/nodeonly/mongoose-test

欢迎拍砖

欢迎关注我的公众号【node全栈】 node全栈.png

12 回复

todo

  • 骨架生成脚本
  • 自动测试gulp
  • 代码测试覆盖率
  • 其他测试(集成测试等)补齐

自动测试gulp和代码测试覆盖率

  • auto test
  • 代码测试覆盖率
npm install --save-dev gulp
npm install --save-dev gulp-mocha
npm install --save-dev gulp-istanbul

创建gulpfilejs

var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha'); 

gulp.task('test', function (cb) {
  gulp.src(['db/**/*.js'])
    .pipe(istanbul()) // Covering files
    .on('finish', function () {
      gulp.src(['test/*.js'])
        .pipe(mocha())
        .pipe(istanbul.writeReports()) // Creating the reports after tests runned
        .on('end', cb);
    });
});

gulp.task('default',['test'], function() {
  gulp.watch(['./db/**/*','./test/**/*'], ['test']);
});

gulp.task('watch',['test'], function() {
  gulp.watch(['./db/**/*','./test/**/*'], ['test']);
});

测试

node_modules/.bin/gulp 

这时,你试试修改测试或源文件试试,看看会不会自动触发测试

当然,如果你喜欢只是测试一次,可以这样做

node_modules/.bin/gulp test 

如果你不熟悉gulp,可以再这里https://github.com/i5ting/js-tools-best-practice/blob/master/doc/Gulp.md学习

如果对测试不太了解,可以看看alsotang的教程 https://github.com/alsotang/node-lessons/tree/master/lesson6

扒出来的好东西

    "test": "./node_modules/.bin/mocha --reporter spec",
    "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot",
    "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot"

测试覆盖率和ci这样写确实很简单

@i5ting 最近按上了gulp,然后照着教程去试了试,发现gulp可以帮助我检查代码的语法错误或者语法不标准。 那么我们可以用gulp来编写测试用例吗?

挖坟。。 其实我想说,这跟mongoose有嘛关系?

先赞一个,留着好好学习

@qianjiahao gulp和grunt,ant,rake,make等是一样的基于task的构建工具,它适合处理批量的,如果只是简单的此时用力,mocha就够了

给出一个比较经典的gulp test相关的task定义

gulp.task('test', ['watch_all'],function (cb) {
  gulp.src(['build/test/**/*.js'])
    .pipe(istanbul()) // Covering files
    .on('finish', function () {
      gulp.src(['build/test/*.js'])
        .pipe(mocha({
					ui : 'bdd',
					reporter: 'spec'
				}))
        .pipe(istanbul.writeReports()) // Creating the reports after tests runned
        .on('end', cb);
    });
});

@airyland 哈哈,说到点了,这篇文章都是node关于tdd的事件

唯一有关的东西,是那mongoose来当练手的学习对象,代码里有体现的

抱着学习mongoose的心态点进来= =结果发现是学习tdd的好东西- -意外收获~~~~

@i5ting 看来得去学学mocha啦

回到顶部