动态创建摩卡测试套件

Dynamically create Mocha Test Suites

我正在尝试实现一个将测试 config/cases 作为输入 (yaml/json) 文件并执行大量断言的应用程序。

case:
 - operation: fetch_user
  args:
  - name: id
    value: 1
 - checks:
   - attribute: username
     expected_value: user1
   - attribute: email
     expected_value: user1@test.com    

我想编写通用测试块 (it()) 来动态执行断言。

我试过了Does mocha/supertest create express server for each test suite?

我正在 index.js 中获取用户信息并在 assertion.js 文件中有断言。

index.js

//read yaml file

const body = userService.get(userId);

body.then(userResponse => {
    const suite = createTestSuite("Test", checks, userResponse);
    suite.run();
});

assertion.js


function createTestSuite(name, checks, userResponse) {
    let suite = new Suite("Moch test");
    suite.addTest(new Test("Check Username", () => {
        expect(userResponse.username).to.equal(checks.expected_username);
    }));

    return suite;
}

--delay 选项应该有所帮助 (docs)。

尝试类似(未测试)的方法:

// test.js
// run with `mocha --delay test.js`

// getData will return a Promise which fulfills with an array of test data
getData().then(testData => {
  describe('mocha tests', function() {
    testData.forEach(data => {
      it('should do something with data', function() {
        // assertion here
      });
    });
  });

  run(); // this is a global which starts the test run
});

--delay 选项导致测试 运行 等待 直到您调用 run(),这允许您执行异步操作(例如,收集一些数据)定义测试之前。

Mocha 目前不支持异步套件,这使得从异步数据源动态生成测试变得很尴尬。