如何在所有 jsamine 测试之前 运行 一个脚本?

How to run a script before all jsamine tests?

我想启动服务器并使用 Jasmine 运行 对其 API 进行测试。

为此,我想确保在 jasmine 运行 进行测试之前 运行 安装好服务器。

我还有很多测试,我把它们分成了多个文件。

我不想在每个测试文件的 beforeAll 挂钩中特别启动服务器,因为它会导致服务器 运行ning 的端口发生冲突。

我想到了 2 个我不知道如何用 Jasmine 做的理论解决方案。

  1. 为 jasmine 命令创建一个全局 before/after 脚本,该脚本在 before/after 所有测试文件中执行。
  2. 有一种方法可以将所有测试文件导入到 Jasmine 文件中,我可以在众所周知的 beforeAll 中进行设置。但是我不知道如何正确导入这些文件,这也使它们都依赖于我的 mainTest 文件。意思是我不能单独执行它们。

附加信息: 我在 node.js 环境中 运行 正在使用 express-server 并正在测试它的 api (每个路由都有它的测试文件)

您可以使用helpers配置。 helpers 目录中的文件将在 运行 所有测试之前执行。例如:

项目结构:

.
├── .babelrc
├── .editorconfig
├── .gitignore
├── .nycrc
├── .prettierrc
├── LICENSE
├── README.md
├── jasmine.json
├── package-lock.json
├── package.json
└── src
    ├── helpers
    │   ├── console-reporter.js
    │   ├── fake-server-setup.js
    │   └── jsdom.js
    └── Whosebug
        ├── 60138152
        ├── 61121812
        ├── 61277026
        ├── 61643544
        ├── 61985831
        └── 62172073

fake-server-setup.js:

const express = require('express');

beforeAll((done) => {
  const app = express();
  global.app = app;
  const port = 3000;
  app.get('/api', (req, res) => {
    res.sendStatus(200);
  });
  app.listen(port, () => {
    done();
    console.log('server is listening on port:' + port);
  });
});

我们将在每个测试文件中使用的 app 变量存储到 global 变量。

a.test.js:

const supertest = require('supertest');
describe('62172073 - a', () => {
  it('should pass', () => {
    return supertest(global.app).get('/api').expect(200);
  });
});

b.test.js:

const supertest = require('supertest');
describe('62172073 - b', () => {
  it('should pass', () => {
    return supertest(global.app).get('/api').expect(200);
  });
});

jasmine.json:

{
  "spec_dir": "src",
  "spec_files": ["**/?(*.)+(spec|test).[jt]s?(x)"],
  "helpers": ["helpers/**/*.js", "../node_modules/@babel/register/lib/node.js"],
  "stopSpecOnExpectationFailure": false,
  "random": true
}

测试结果:

Executing 2 defined specs...
Running in random order... (seed: 03767)

Test Suites & Specs:
(node:54373) ExperimentalWarning: The fs.promises API is experimental

1. 62172073 - bserver is listening on port:3000

   ✔ should pass (51ms)

2. 62172073 - a
   ✔ should pass (5ms)

>> Done!


Summary:

  Passed
Suites:  2 of 2
Specs:   2 of 2
Expects: 0 (none executed)
Finished in 0.085 seconds