【问题标题】:Drop database before anything先删除数据库
【发布时间】:2017-11-17 05:56:00
【问题描述】:

我已经看过很多关于这个问题的答案,但其中任何一个都对我有用,我不知道为什么。

所以我想在运行测试之前和添加一些之后删除我的数据库中的所有数据。这是我到目前为止所做的:

const db = require('../models');

describe('Setup database for testing', () => {
    before('Sync and create data', done => {
        db.sequelize
            .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})
            .then(() => {
                db.User.sync({force: true});
            })

            // Create everything the tests need here
            .then(() => {
                db.User.create({username: 'foo', password: 'secret', email: 'foo@local.dev'});
            })

            .then(() => {
                db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null, {raw: true});
            })
            .then(() => {
                done();
            });
    });
});

当我在我的测试文件夹上运行 mocha 时,我没有任何错误,没有告诉我 before 钩子正在运行(甚至测试标题也没有显示)。但是该文件正在运行,因为当我在其中编写虚拟代码时,出现了错误。

【问题讨论】:

    标签: javascript node.js mocha.js sequelize.js


    【解决方案1】:

    您需要在 describe 中至少进行一项测试才能运行 before 挂钩。

      describe('Setup database for testing', () => {
        before('Sync and create data', done => {
            db.sequelize
                .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})
                .then(() => {
                    db.User.sync({force: true});
                })
    
                // Create everything the tests need here
                .then(() => {
                    db.User.create({username: 'foo', password: 'secret', email: 'foo@local.dev'});
                })
    
                .then(() => {
                    db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null, {raw: true});
                })
                .then(() => {
                    done();
                });
        });
    
    
        //add a test for the before hook to run 
        it("runs", function () {
            console.log("test");
        });
    });
    

    【讨论】:

    • 感谢它的工作!但现在我有错误Cannot delete or update a parent row: a foreign key constraint fails,或者我执行SET FOREIGN_KEY_CHECKS=0...
    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多