数据驱动的 Jestjs 测试

Data driven Jestjs tests

有没有办法用 Jestjs 编写更多数据驱动的测试?

我想到了这样的东西:

    it('assignments and declarations', () => {

    testCases.forEach(function (testCase) {
        const slx = fs.readFileSync(testDirectory + 'slx/' + testCase.slx, 'utf-8');

        const document = compiler.parse(slx);

        const lmsGenerator = new LMSGenerator(document);
        const lms = lmsGenerator.generate();

        const expected = fs.readFileSync(testDirectory + 'lms/' + testCase.lms, 'utf-8');

        expect(expected).toBe(lms);
    });
});

我从文件中读取了输入和预期的输出。文件(以及输入和输出之间的 link)保存在一个包含对象的数组中。问题是我丢失了多个 it() 函数的特定错误消息。

有没有办法做得更好?或者在预期调用失败的情况下使用单独的消息?

您为每个测试用例创建一个 it 块并将它们捆绑在一个 describe 块中。现在您将收到每个损坏案例的错误消息,并且测试不会在第一次失败后停止。

describe('assignments and declarations for', () => {
  testCases.forEach(function (testCase) {
    it(`case ${testCase}`, () => {
      const slx = fs.readFileSync(testDirectory + 'slx/' + testCase.slx, 'utf-8');
      const document = compiler.parse(slx);
      const lmsGenerator = new LMSGenerator(document);
      const lms = lmsGenerator.generate();
      const expected = fs.readFileSync(testDirectory + 'lms/' + testCase.lms, 'utf-8');
      expect(expected).toBe(lms);
    });
  });
});