简体   繁体   English

如何在 typescript-node 项目中配置 jest-mongodb(@shelf/jest-mongodb)?

[英]How to configure jest-mongodb(@shelf/jest-mongodb) in typescript-node project?

I am working on integration testing, So getting a data from database makes testcase execution slower.我正在进行集成测试,因此从数据库获取数据会使测试用例执行速度变慢。 Tried with jest-mongodb to set up a temp db.尝试使用 jest-mongodb 设置临时数据库。 but could not find a proper documentation for setting up jest-mongodb in typescript-nodejs project.但找不到在 typescript-nodejs 项目中设置 jest-mongodb 的正确文档。 please help me to overcome this issue.请帮我解决这个问题。

test.ts(db configuration file based on this test suites connect to db) test.ts(基于此测试套件的数据库配置文件连接到数据库)

export default {    
    jwtPrivateKey: 'secretkey',
    // Testing Database configuration
    MongoDB: {
        dbConfig: {
            user: 'user name',
            host: 'some host',
            port: 'some port',
            authMechanism: 'some mechanism',
            authSource: 'access level',
            dbName: 'database name',
            metadata: 'initializer'
        }
    }
};

Create the file: typings/global.d.ts :创建文件: typings/global.d.ts

declare namespace NodeJS {
  export interface Global {
    __MONGO_URI__: string;
  }
}

Then, in your tsconfig.json :然后,在您的tsconfig.json

{
  "compilerOptions": { ... },
  "include": ["./src/**/*", "./typings/*"]
}

One way to have this setup is as follows:进行此设置的一种方法如下:

Configure Jest with TypeScript via Babel:通过 Babel 使用 TypeScript 配置 Jest:

yarn add --dev babel-jest @babel/core @babel/preset-env @babel/preset-typescript

Then in your babel config you would have:然后在您的 babel 配置中,您将拥有:

// babel.config.js
 module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript"
  ]
};

You can find the docs here Jest TypeScript support via Babel你可以在这里找到文档Jest TypeScript support via Babel

And finally add @shelf/jest-mongodb to your jest.config.js最后将 @shelf/jest-mongodb 添加到 jest.config.js

// jest.config.js
module.exports = {
  preset: "@shelf/jest-mongodb",
  verbose: true
};

Now you're good to go.现在你可以走了。 In your test file, you'll have access to the test db URL, through:在您的测试文件中,您可以通过以下方式访问测试数据库 URL:

process.env.MONGO_URL

Or或者

const globalAny: any = global;
globalAny.__MONGO_URI__

It looks like @shelf/jest-mongodb has removed the exposed global variables and has replaced them with a single environment variable instead.看起来@shelf/jest-mongodb已经删除了公开的全局变量,并用一个环境变量代替了它们。 Conveniently this works around the need to declare global typings.方便地,这可以解决声明全局类型的需要。

From https://github.com/shelfio/jest-mongodb#readme :来自https://github.com/shelfio/jest-mongodb#readme

const {MongoClient} = require('mongodb');

describe('insert', () => {
  let connection;
  let db;

  beforeAll(async () => {
    connection = await MongoClient.connect(process.env.MONGO_URL, { // <= MONGO_URL env var set
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    db = await connection.db(); // <= env var (presumably) includes the db so no longer need to pass this
  });

  afterAll(async () => {
    await connection.close();
  });
});

There is therefore no need to modify your tsconfig.json config to support this.因此无需修改您的tsconfig.json配置来支持这一点。

Jest MongoDB provides all required configuration to run your tests using MongoDB. Jest MongoDB 提供了使用 MongoDB 运行测试所需的所有配置。 Described Here此处描述

First you need to install @shelf/jest-mongodb,首先你需要安装@shelf/jest-mongodb,

yarn add @shelf/jest-mongodb --dev

then Specify preset in your Jest configuration:然后在您的 Jest 配置中指定预设:

{
  "preset": "@shelf/jest-mongodb"
}

Then start Writing your tests.然后开始编写测试。 like :喜欢 :

const {MongoClient} = require('mongodb');

describe('insert', () => {
  let connection;
  let db;

  beforeAll(async () => {
    connection = await MongoClient.connect(global.__MONGO_URI__, {
      useNewUrlParser: true,
    });
    db = await connection.db(global.__MONGO_DB_NAME__);
  });

  afterAll(async () => {
    await connection.close();
    await db.close();
  });

  it('should insert a doc into collection', async () => {
    const users = db.collection('users');

    const mockUser = {_id: 'some-user-id', name: 'John'};
    await users.insertOne(mockUser);

    const insertedUser = await users.findOne({_id: 'some-user-id'});
    expect(insertedUser).toEqual(mockUser);
  });
});

There's no need to load any dependencies.无需加载任何依赖项。 See Jest-MongoBD Documentation on GitHub.请参阅 GitHub 上的 Jest-MongoBD文档

[DO VOTE TO THIS ANSWER, IF ITS HELPFUL TO YOU] [请投票给这个答案,如果它对你有帮助]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM