node.js - Jest 的 globalSetup 使我的测试无法被识别

标签 node.js mongodb unit-testing testing jestjs

所以我关注了this example在开 Jest 时用 mongodb 进行测试,但是在配置完所有内容后,我在运行 Jest 时得到了这个:

enter image description here

如果我从 jest.config.js 中删除 globalSetup,尽管由于 mongo-enviroment 和拆解配置依赖于 globalSetup 而出现错误,但测试仍会出现: enter image description here

如果我运行 jest --debug 我会得到这个:

{
  "configs": [
    {
      "automock": false,
      "browser": false,
      "cache": true,
      "cacheDirectory": "/tmp/jest_rs",
      "clearMocks": false,
      "coveragePathIgnorePatterns": [
        "/node_modules/"
      ],
      "detectLeaks": false,
      "detectOpenHandles": false,
      "errorOnDeprecated": false,
      "filter": null,
      "forceCoverageMatch": [],
      "globals": {},
      "haste": {
        "providesModuleNodeModules": []
      },
      "moduleDirectories": [
        "node_modules"
      ],
      "moduleFileExtensions": [
        "js",
        "json",
        "jsx",
        "node"
      ],
      "moduleNameMapper": {},
      "modulePathIgnorePatterns": [],
      "name": "9f5155d702743ad8d949d6d219c1bc22",
      "prettierPath": null,
      "resetMocks": false,
      "resetModules": false,
      "resolver": null,
      "restoreMocks": false,
      "rootDir": "/home/mauricio/work/growthbond/gbnd1",
      "roots": [
        "/home/mauricio/work/growthbond/gbnd1"
      ],
      "runner": "jest-runner",
      "setupFiles": [
        "/home/mauricio/work/growthbond/gbnd1/node_modules/regenerator-runtime/runtime.js"
      ],
      "setupTestFrameworkScriptFile": "/home/mauricio/work/growthbond/gbnd1/testConfig/setupScript.js",
      "skipFilter": false,
      "snapshotSerializers": [],
      "testEnvironment": "/home/mauricio/work/growthbond/gbnd1/testConfig/mongo-environment.js",
      "testEnvironmentOptions": {},
      "testLocationInResults": false,
      "testMatch": [
        "**/__tests__/**/*.js?(x)",
        "**/?(*.)+(spec|test).js?(x)"
      ],
      "testPathIgnorePatterns": [
        "/node_modules/"
      ],
      "testRegex": "",
      "testRunner": "/home/mauricio/work/growthbond/gbnd1/node_modules/jest-jasmine2/build/index.js",
      "testURL": "http://localhost",
      "timers": "real",
      "transform": [
        [
          "^.+\\.jsx?$",
          "/home/mauricio/work/growthbond/gbnd1/node_modules/babel-jest/build/index.js"
        ]
      ],
      "transformIgnorePatterns": [
        "/node_modules/"
      ],
      "watchPathIgnorePatterns": []
    }
  ],
  "globalConfig": {
    "bail": false,
    "changedFilesWithAncestor": false,
    "collectCoverage": false,
    "collectCoverageFrom": null,
    "coverageDirectory": "/home/mauricio/work/growthbond/gbnd1/coverage",
    "coverageReporters": [
      "json",
      "text",
      "lcov",
      "clover"
    ],
    "coverageThreshold": null,
    "detectLeaks": false,
    "detectOpenHandles": false,
    "errorOnDeprecated": false,
    "expand": false,
    "filter": null,
    "globalSetup": "/home/mauricio/work/growthbond/gbnd1/testConfig/setup.js",
    "globalTeardown": "/home/mauricio/work/growthbond/gbnd1/testConfig/teardown.js",
    "listTests": false,
    "maxWorkers": 3,
    "noStackTrace": false,
    "nonFlagArgs": [],
    "notify": false,
    "notifyMode": "always",
    "passWithNoTests": false,
    "projects": null,
    "rootDir": "/home/mauricio/work/growthbond/gbnd1",
    "runTestsByPath": false,
    "skipFilter": false,
    "testFailureExitCode": 1,
    "testPathPattern": "",
    "testResultsProcessor": null,
    "updateSnapshot": "new",
    "useStderr": false,
    "verbose": true,
    "watch": false,
    "watchman": true
  },
  "version": "23.6.0"
}

注意

"testMatch": [
        "**/__tests__/**/*.js?(x)",
        "**/?(*.)+(spec|test).js?(x)"
      ],

看起来非常好。

相关文件

jest.config.js:

module.exports = {
    globalSetup: './testConfig/setup.js',
    globalTeardown: './testConfig/teardown.js',
    testEnvironment: './testConfig/mongo-environment.js',
    setupTestFrameworkScriptFile: './testConfig/setupScript.js',
    verbose: true
}

setup.js (globalSetup):

const path = require('path');
const fs = require('fs');
const MongodbMemoryServer = require('mongodb-memory-server');
const globalConfigPath = path.join(__dirname, 'globalConfig.json');

const mongod = new MongodbMemoryServer.default({
  instance: {
    dbName: 'jest'
  },
  binary: {
    version: '3.2.18'
  },
  autoStart: false,
});

module.exports = async () => {
  if (!mongod.isRunning) {
    await mongod.start();
  }

  const mongoConfig = {
    mongoDBName: 'jest',
    mongoUri: await mongod.getConnectionString()
  };

  // Write global config to disk because all tests run in different contexts.
  fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig));
  console.log('Config is written');

  // Set reference to mongod in order to close the server during teardown.
  global.__MONGOD__ = mongod;
  process.env.MONGO_URL = mongoConfig.mongoUri;
};

拆解.js:

module.exports = async function() {
    await global.__MONGOD__.stop();
  };

mongo-environment.js:

const NodeEnvironment = require('jest-environment-node');
const path = require('path');
const fs = require('fs');
const globalConfigPath = path.join(__dirname, 'globalConfig.json');

module.exports = class MongoEnvironment extends NodeEnvironment {
  constructor(config) {
    super(config);
  }

  async setup() {
    console.log('Setup MongoDB Test Environment');

    const globalConfig = JSON.parse(fs.readFileSync(globalConfigPath, 'utf-8'));

    this.global.__MONGO_URI__ = globalConfig.mongoUri;
    this.global.__MONGO_DB_NAME__ = globalConfig.mongoDBName;

    await super.setup();
  }

  async teardown() {
    console.log('Teardown MongoDB Test Environment');

    await super.teardown();
  }

  runScript(script) {
    return super.runScript(script);
  }
};

user.test.js(mongodb相关测试):

const MongoClient= require('mongodb');
const User = require('../../db/models/user');
let connection;
let db;

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

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


describe('Password Encription', async () => {

    const uEmail = 'test@a.com';
    const uPass = '123test';
    var testUser = new User({
        email:uEmail ,
        password: uPass
    });

    await testUser.save()

    test('Encripted password string is different to plain password', async () => {
      user = await User.findOne({ email: uEmail });
      expect(user.password).not.toEqual(uPass);
    });

    test('ComparePassword method verify that plain password is the same that encrypted password', async () => {
      rightPassword = await user.comparePassword(uPass);
      expect(rightPassword).toBeTrue();
    });

    test('ComparePassword method verify that altered plain password is not the same that encrypted password', async () => {
      wrongPassword = await user.comparePassword(uPass+'random');
      expect(rightPassword).not.toBeTrue();
    });


});

authService.test.js:

require('dotenv').config()
const authS = require('../../services/authService');
const jwt = require('jsonwebtoken');

describe('Auth Services',()=>{
    const payload = {test:'This is a test'}
    const user = {id:101}
    const mockSecret = 'SECRET123HAAJAHJSoafdafda'
    const token = authS.jwtSign(user,payload)
    test('JWT sign', () => {
        expect(authS.jwtSign(user,payload)).toBeString();
    });

    test('JWT verify different secret', ()=>{
        badToken = jwt.sign(
            payload,
            mockSecret,
            { subject:String(user.id),
              expiresIn:'1h' 
            }
        );
        expect(()=>authS.jwtVerify(badToken)).toThrowError(jwt.JsonWebTokenError)
    })

    test('JWT verify payload', ()=>{
        expect(authS.jwtVerify(authS.jwtSign(user,payload))).toMatchObject(payload)
    })

})

我的环境:

Node v11.0.0

开 Jest 23.6.0

事实上,如果我发表评论,我知道我的测试非 mongodb 相关运行

globalSetup: './testConfig/setup.js',
globalTeardown: './testConfig/teardown.js',
testEnvironment: './testConfig/mongo-environment.js',

来自 jest.config.js :

enter image description here

最佳答案

我的问题是我有另一个 GlobalSetup 文件,它们相互冲突。在我的自定义 GlobalSetup 中,我导入了 @Shelf/jest-mongodb/setup 并将其添加到我的。

const jestMongoSetup = require("@shelf/jest-mongodb/setup")

module.exports = async () => {
    process.env.TZ = "UTC" //My config
    await jestMongoSetup()
}

关于node.js - Jest 的 globalSetup 使我的测试无法被识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137475/

相关文章:

mongodb - 需要在 mongodb 中使用自定义结果填充 block 中所需的结果

c# - 如何使用 FakeItEasy 验证 FindOneAndUpdateAsync 方法针对伪造的 MongoCollection 运行?

r - 如何为 R 包中的 cpp 函数编写测试?

node.js - 如果没有这样的文件,npm 模块将不会执行,但它确实存在

javascript - 股票市场 API Node.JS

node.js - 用 node.js 编写的 CDN 服务器

mongodb - 在 Kubernetes 上为 mongodb 创建 StatefulSet 时出错

ios - Xcode 7 代码覆盖率 - 蓝色进度和灰色线条是什么意思?

c++ - 如何对 void 函数进行单元测试 CPPUNIT

node.js - brew install node 卡在 `make install`