【问题标题】:Is there a way to write a beforeEach globally?有没有办法在全局范围内编写 beforeEach ?
【发布时间】:2018-07-01 16:38:33
【问题描述】:

我正在尝试使用 sequelize 编写测试,并且我想在每次测试之前截断所有表。如果可能的话,我不想在每个测试文件中编写或运行它。有谁知道这样做的方法吗?

看来 jest 应该支持这样的东西。

我目前正在尝试使用 globalSetup,但那是 beforeAll。

我还有一个问题是,当我运行 globalSetup 时,我做了这样的事情:

  module.exports = () => {                                                                                                                                                                                
    sequelize.db.sync({ force: true })
  }

二分之一有效。所以我猜这是在我需要它同步运行时异步运行的。

【问题讨论】:

    标签: node.js sequelize.js jestjs


    【解决方案1】:

    一种方式:

    sequelize.db.sync({ force: true }).then(() => {
        // write you test code here
        // Or
        // or call the function from here to perform your test
    })
    

    或者你也可以这样做:

    // trunk.js
    
    module.exports = () => {                                                                                                                                                                                
        sequelize.db.sync({ force: true })
    }
    
    // test.js
    
    const trunk = require('./trunk');
    
    module.exports = () => { 
        trunk.then(() => {
            // write you test code here
        })
    }
    

    【讨论】:

    • Hrm... 所以这简化了数据库清理代码,但是有没有办法在每个之前把它放在一个全局中?我不喜欢重复调用以清除每个测试的数据库。 :(
    猜你喜欢
    • 2012-04-29
    • 2012-02-16
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2017-08-26
    相关资源
    最近更新 更多