美文网首页
创建数据库实例

创建数据库实例

作者: 黑山老水 | 来源:发表于2017-08-28 08:03 被阅读40次

    创建并且保存实例

    打开test里的create_test.js文件:

    1. 进入 user.js 获取创建好的user模型
    2. 用user模型创建实例
    3. 保存这个实例
    4. 用robomongo检查
    //插入记录
    
    //引用断言
    const assert = require('assert');
    
    //access user.js code
    //get the entire user collection
    const User = require('../src/user');//“../” = go up one dir
    
    //describe function
    describe('Creating records', () => { //describe string and it function
             it('saves a user', () => {  //individual it statement
                //create new user: Use model to create the instance
                const joe = new User({ name: 'Joe'});
                //save record
                joe.save();
                });
             });
    

    IT函数中没有断言的情况下,会默认测试通过
    command + R 刷新


    测试

    1. 测试流程
    测试流程
    2. hook function

    所有在数据库上的操作都是异步的,所以mocha需要暂停

    3. done回调

    打开test_helper.js

    //run before each test
    beforeEach((done) => {//当hook调用done时,即告诉mocha一切就绪,可以进行下一个测试
               //delete all the records in this collection ASAP
               mongoose.connection.collections.users.drop(() => {
                                                          //Ready to run the next test
                                                          done();
                                                          });
               }
    );
    

    添加断言

    回到create_test.js
    数据库的每一个操作都需要时间,所以异步其实是数据库的一个特征,所以要等待记录实例完毕,再进行断言,再进行下一个测试

    1. save()返回的promise

    当我们刚刚创建好instance的时候,这个record存在于缓存里或者说还在mocha之中。此时mongoose会自动给这instance创建一个flag:XXXisNew === true。反之则为false。所以我们可以使用这个flag来进行断言。

    //describe function
    describe('Creating records', () => { //describe string and it function
             it('saves a user', () => {  //individual it statement
                //create new user: Use model to create the instance
                const joe = new User({ name: 'Joe'});
                //save record
                joe.save()
                .then(() => {
                                //针对Joe是不是加入了记录,我们可以给出一个断言
                      assert(!joe.isNew);
                                });
                });
             });
    
    2. 当断言结束,同样也给一个done回调
    //describe function
    describe('Creating records', () => { //describe string and it function
             it('saves a user', (done) => {  //individual it statement
                //create new user: Use model to create the instance
                const joe = new User({ name: 'Joe'});
                //save record
                joe.save()
                .then(() => {
                                //针对Joe是不是加入了记录,我们可以给出一个断言
                      assert(!joe.isNew);
                      done();//同样给一个done回调
                                });
                });
             });
    

    相关文章

      网友评论

          本文标题:创建数据库实例

          本文链接:https://www.haomeiwen.com/subject/jblwdxtx.html