【问题标题】:How to configure In-memory mongodb?如何配置内存中的mongodb?
【发布时间】:2020-04-07 14:49:20
【问题描述】:

我正在使用 MongoDB 数据库对我的 NodeJS-Typescript 应用程序进行集成测试。我使用 Jest 作为测试框架。如何用可用于测试的内存数据库(mongoDb)替换真实的数据库配置。谁能帮我配置一下?

config.ts

/**
 * @file Configuration file - Testing Configuration.
 */

export default {
    jwtPrivateKey: '11234.xsdfcswfe.23rcscdsfg',
    // Testing Database configuration
    MongoDB: {
        dbConfig: {
            user: 'xxxx',
            password: 'xxxx',
            host: '11.222.333.444',
            port: '27017',
            authMechanism: 'SCRAM-SHA-1',
            authSource: 'permissionlevel',
            dbName: 'sample_db'
        }
    }

};

【问题讨论】:

标签: javascript node.js mongodb typescript jestjs


【解决方案1】:

您可以在运行测试之前设置一个真实的测试数据库,并在运行测试后将其删除。在这个例子中(使用mongoose),甚至在运行测试之前就清理了数据库(以防上次运行出现问题)

mongoose.connect('mongodb://localhost/testing_db')


const db = mongoose.connection

db.on('error', err => {
        console.error(err.toString())
        done(err)
      })
db.once('open', () => {
        db.db.dropDatabase(() => {
          done()
        })
      })

这会删除testing_db

【讨论】:

    【解决方案2】:

    我已经开始使用 @shelfio/jest-mongodb 到目前为止它运行良好。

    他们网站上的文档很棒,并且 repo 有很好的例子。

    这也是 jest 在他们的网站上推荐的库 - Using with MongoDB,所以如果你还没有的话,我建议你开始看看这个。

    【讨论】:

    • 是的,我已经提到了。在我的情况下,我需要连接测试数据库进行集成测试。所以我需要在 config.ts 中设置一个内存配置,这样我就可以避免每个测试文件中的 beforeAll 和 afterAll 块。
    • 啊,明白了。没有为该用例尝试完整的内存,但您是否考虑过启动一个 docker MongoDB 容器,然后针对该实例运行测试?是否会起到同样的作用,并且可以防止额外的拆除需要,因为它无论如何都会被破坏?
    【解决方案3】:

    工作几个小时后。我配置了适合我的 config.ts。

    /**
     * @file Configuration file - Testing Configuration.
     */
    
    // configuring In-memory mongodb
    const globalAny:any = global;
    const inMemoryUri= globalAny.__MONGO_URI__
    let uri=inMemoryUri.split('/')
    let hostPort=uri[2].split(':')
    
    export default {    
        jwtPrivateKey: '121231231fbuyfg.hfvufuewfr3452',
        // Testing Database configuration
        MongoDB: {
            dbConfig: {
                user:'',
                host: hostPort[0],
                port: '27017',
                authMechanism: 'SCRAM-SHA-1',
                authSource: 'permissionlevel',
                dbName: 'jest'
            }
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 2012-01-06
      • 2021-08-19
      • 2021-06-15
      • 2018-03-23
      • 1970-01-01
      • 2023-03-09
      • 2010-10-08
      相关资源
      最近更新 更多