猫鼬模型&集成测试竞争条件

时间:2016-10-10 23:36:05

标签: node.js mongodb mongoose hapi.js

未能通过Twitter或Mongoose JS Gitter频道找到这些问题的任何答案,并希望得到一些帮助。

我正在使用Hapi.JS和Mongoose编写API。我正在使用测试数据库进行集成测试。我发现的是,如果我在多个描述块之后清除数据库,则会对我在后续描述块中保存和运行查询的能力产生负面影响。我将在下面留下一些带注释的代码。

如何在每次测试后清除数据库,并且没有任何影响其他测试的竞争条件?

'use strict'

//this test will pass when run alone
// it clears the db at the end of it's run

let testConfig = require('../fixtures/fixtures.js')
let User = require('../../models/user.js')
let Bucket = require('../../models/bucket.js')
let BucketFactory = require('../../factories/bucket-factory.js')
let request = require('request')
let bluebird = require('bluebird')
let mongoose = require('mongoose')
mongoose.Promise = bluebird


describe('Buckets API', function() {

    it('should get all buckets', function(done){
        request.get(`${testConfig.testConfig.testUrl}/buckets`, (err, response, body)=>{
            if (err){ throw new Error(err)}
            expect(response.statusCode).toBe(200)
            done()
        })
    })

    it('should get a bucket by its id', function (done) {
        request.get(`${testConfig.testConfig.testUrl}/buckets/${mongoose.Types.ObjectId()}`, (err, response, body)=>{
            expect(response.statusCode).toBe(200)
            done()
        })
    });

    it('should post it', function (done) {
        let testBucket = {name: "Drill", userId: mongoose.Types.ObjectId()}
        request.post(`${testConfig.testConfig.testUrl}/buckets`, {json: testBucket}, (err, response, body)=>{
            if(err){ throw new Error(err)}
            expect(response.statusCode).toEqual(200)
            done()
        } )
    });
    // i dont need this afterEach
    // but for illustrative purposes it will mess up the latter test
    // which will pass if i run it by itself
    // but it shouldnt right?
    afterEach((done)=>{
        Bucket.remove({}).then(()=>{done()})
    })
})

describe('findByAndUpdate', function () {
    beforeEach((done)=>{
        // this factory creates and saves a bucket
        // i've verified this by checking the test database manually
        let newBucket = BucketFactory
        done()
    })
    it('should find and update', function (done) {
        Bucket.find({}).exec()
            .then((data)=>{
                request.put(`${testConfig.testConfig.testUrl}/buckets/${data._id}`, {json: {name: 'Marvel'}}, (err, response, body)=>{
                    if(err){ throw new Error(err)}
                    console.log(body)
                    expect(response.statusCode).toEqual(200)
                    done()
                } )
            })

    });

    afterEach((done)=>{
        Bucket.remove({}).then(()=>{done()})
    })
});

0 个答案:

没有答案