Mocha: Not able to delete table and recreate it in mocha using vogels(dynamodb)

Created on 26 Jul 2017  路  3Comments  路  Source: mochajs/mocha

I think I am missing something very fundamental. I tried creating deleting and creating table outside. It worked. The part under beforeEach(for deleting and recreating) is not working though it does not show any error.

Here is the code that worked:

const vogels = require('vogels');
if (process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development") {
    vogels.AWS.config.update({ accessKeyId: "myKeyId", secretAccessKey: "secretKey", region: "us-west-2" });
    vogels.dynamoDriver(new vogels.AWS.DynamoDB({ endpoint: 'http://localhost:8000' }));
} else {
    vogels.AWS.config.update({accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY, region: process.env.AWS_REGION});
}

function wait(ms){
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
        end = new Date().getTime();
    }
}


const DeliveryOrder = require("../api/models/DeliveryOrder");

vogels.createTables({
}, function(err) {
    if (err) {
        console.log('Error creating tables: ', err);
    } else {
        console.log('First creation');
        DeliveryOrder.deleteTable(function(err) {
            if (err) {
                console.log('Error deleting table: ', err);
            } else {
                console.log('Table has been deleted');
                vogels.createTables({
                }, function(err) {
                    if (err) {
                        console.log('Error creating tables: ', err);
                    } else {
                        console.log('Tables have been created');
                    }
                });
            }
        });
    }
});

I tried doing the very same in mocha. it does not run or throw errors(I know this because none of the messages in console log are printed). I was under the impression that mocha should be able to run any js code as long as I require the necessary files. Here is my test file:

process.env.NODE_ENV = 'test'; //Just being safe. 
let vogels = require('vogels');
vogels.AWS.config.update({ accessKeyId: "myKeyId", secretAccessKey: "secretKey", region: "us-west-2" });
vogels.dynamoDriver(new vogels.AWS.DynamoDB({ endpoint: 'http://localhost:8001' }));

//Require the dev-dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../server');
let should = chai.should();
const DeliveryOrder = require("../api/models/DeliveryOrder");
const _      = require('lodash');
chai.use(chaiHttp);


describe('DeliveryOrders', () => {

    function wait(ms){
        var start = new Date().getTime();
        var end = start;
        while(end < start + ms) {
            end = new Date().getTime();
        }
    }
    beforeEach(() => { //Before each test we empty the database
        console.log("in before ............")
        vogels.createTables({
        }, function(err) {
            if (err) {
                console.log('Error creating tables: ', err);
            } else {
                console.log('First creation');
                DeliveryOrder.deleteTable(function(err) {
                    if (err) {
                        console.log('Error deleting table: ', err);
                    } else {
                        console.log('Table has been deleted');
                        vogels.createTables({
                        }, function(err) {
                            if (err) {
                                console.log('Error creating tables: ', err);
                            } else {
                                console.log('Tables have been created');
                            }
                        });
                    }
                });
            }
        });

        console.log("in after ............")
    });


    /*
     * Test the /GET route
     */

    describe('POST DO', () => {
        it('should throw an error on create do with empty data', (done) => {
            let doData = {

            }
            chai.request(server)
                .post('/api/dos')
                .send(doData)
                .end((err, res) => {
                    res.should.have.status(400);
                    res.body.should.have.property('error');
                    // res.body.error.should.have.property('message').eql('LR Number Missing');
                    done();  
                })
        })



        it('should create a delivery order', (done) => {
            let doData = {
                "deliveryOrderNumber" : "03.05.2017",
                "companyId" : "BMM",
                "locationId" : "TADIPATRI",
                "branch" : "KPCL",
                "createdDate" : "2017",
                "vesselName" : "MV ANANGEL VICTORY",
                "cargo" : "coal",
                "cargoType" : "steamCoal",
                "cargoGrade" : "SOUTH AFRICA",
                "partyName" : "PENNA CEMENTS LTD",
                "subPartyName" : "PENNA CEMENTS LTD",
                "totalIssuedQuantity" : "5000",
                "transinIssuedQuantity" : "1000",
                "companyInchargeName" : "RAMESH BABU",
                "companyInchargePhoneNumber" : "8096696663.0",
                "transinInchargeName" : "RAMESH REDDY",
                "transinInchargePhoneNumber" : "9666777636.0",
                "tolerance" : "1",
                "billOfEntry" : {
                    "billEntryNumber" : "9106716/31.03.2017",
                    "customHouseAgent" : "NL",
                    "portOfLoading" : "RICHARDS BAY",
                    "countryOfOrigin" : "SOUTH AFRICA",
                    "grossWeight" : "5000",
                    "seller" : "SWISS SINGAPORE OVERSEAS ENTERPRISES",
                    "netValuePrice" : "3365568"
                },
                "completedQuantity" : "999.21",
                "material" : "coal-steamCoal-SOUTH AFRICA",
                "status" : "inactive",
                "deliveryOrderType" : "has_a_tdo",
                "deliveryOrderTypeId": ["TDO001"]

            }

            chai.request(server)
                .post('/api/dos')
                .send(doData)
                .end((err, res) => {
                    // console.log("Post response", res.body);
                    res.should.have.status(200);
                    res.body.should.have.property('data');
                    done();  
                })
            // DeliveryOrder.destroy('03.05.2017', function (err) {
            //       if (err) {
            //         console.log('Error deleting item: ', err);
            //       } else {
            //         console.log('Item has been deleted');
            //       }
            // });

            // DeliveryOrder.deleteTable(function(err) {
            //   if (err) {
            //     console.log('Error deleting table: ', err);
            //   } else {
            //     console.log('Table has been deleted');
            //   }
            // });
            //  wait(2000);

        })

    });


    describe('/GET delivery orders by DO Number', () => {
        it('it should GET all the delivery orders', (done) => {
            chai.request(server)
                .get('/api/do/03.05.20178')
                .end((err, res) => {
                    console.log("GET by DO number response", res.body);
                    res.should.have.status(200);
                    res.body.should.be.a('object');
                    // res.body.data.length.should.be.eql(0);
                    done();
                });
        });
    });


    describe('/GET delivery orders by Location Id', () => {
        it('it should GET all the delivery orders', (done) => {
            chai.request(server)
                .get('/api/do/location/tadipatri')
                .end((err, res) => {
                    console.log("GET by Location Id response", res.body);
                    res.should.have.status(200);
                    res.body.should.be.a('object');
                    // res.body.data.length.should.be.eql(0);
                    done();
                });
        });
    });


    describe('/GET delivery orders by Branch Id', () => {
        it('it should GET all the delivery orders', (done) => {
            chai.request(server)
                .get('/api/do/branch/kpcl')
                .end((err, res) => {
                    res.should.have.status(200);
                    res.body.should.be.a('object');
                    // res.body.data.length.should.be.eql(0);
                    done();
                });
        });
    });

});

Most helpful comment

@helloravi your beforeEach function has asynchronous code in it, and as such, should take a done parameter that is called after you're finished with the async work. Currently, your tests are running before your databases are created because mocha isn't waiting until your async work is complete.

An example can be found here - https://mochajs.org/#asynchronous-hooks

All 3 comments

@helloravi your beforeEach function has asynchronous code in it, and as such, should take a done parameter that is called after you're finished with the async work. Currently, your tests are running before your databases are created because mocha isn't waiting until your async work is complete.

An example can be found here - https://mochajs.org/#asynchronous-hooks

@johnkpaul That seems to be the issue :) Thank you very much.

@johnkpaul Thanks for resolving this!

@helloravi I'm going to go ahead and close this since it sounds like you were able to get what you needed, but let us know if you are still having trouble -- we can always reopen it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertherber picture robertherber  路  3Comments

smithamax picture smithamax  路  4Comments

jamietre picture jamietre  路  3Comments

EdvinOlofsson picture EdvinOlofsson  路  3Comments

CADBOT picture CADBOT  路  3Comments