node mocha 测试 一个超简单的小例子
发布于 8 年前 作者 Yhaojing 4425 次浏览 来自 分享

以下只是mocha特别简单的小例子,请勿喷,有错请指出,谢谢

import request from 'superagent';
import 'should';
let base = 'http://localhost:3000';

describe('login', function () {
    it('login 验证', function (done) {
        request
            .post(base+'/api/users/login')
            .send({n:'1234', p: '1'})
            .end(function (err, res) {
                console.log(res)
                res.status.should.eql(200)
                done()
            })
    })
})

describe('user', function () {
    it('获取用户信息', function (done) {
        request
            .get(base+'/api/users/user')
            .set('token','')
            .end((err, res) => {
                console.log('test user:', res.body)
                done();
            })
    })
}) 

这是controller层代码的测试,分别一个简单的get方法和post方法,具体的断言可以根据实际情况加入这里只是简单的展示一下使用方法。

import should from 'should';
import FuncDao from '../../dao/func';
const funcImpl = new FuncDao();

describe('dao', function () {
    describe('getFuncInfoByUserId', function () {
        it('获取funcId', function (done) {
            funcImpl.getFuncInfoByUserId('db32f820-0c26-11e6-aacc-7fcf053d8408')
                .then((res) => {
                    console.log('result:', res);
                    done();
                })
        })
    })
});

这是操作数据库层的代码显示, getFuncInfoByUserId 是其中的一个方法,里面是异步的所以使用.then的形式,目前正在研究可否使用async /await 据悉ava 是支持的, mocha我正在学习,但是这个不影响测试。 由于使用了es6 要使用babel-cli进行转码 npm相关的依赖, 在test 目录下创建 mocha.opts, 内容如下:

--compilers js:babel-core/register

之后就可以直接运行: mocha 相关测试类

回到顶部