设置笑话测试

时间:2019-03-26 20:09:17

标签: javascript node.js unit-testing jestjs

我正在开玩笑地在生成YAML和JSON的工具上运行单元测试,这不是纯JavaScript。 Jest让我可以实际测试输出中的值,因此非常方便。

我有一个目录,组件:

/workdir/components/
├── component1
└── component2

在每个组件中,我都有一个测试目录,其中包含一些有趣的测试。这是一个示例测试:

// Define tests for component
//
const _ = require("lodash");
const componentName = 'my_component';
const {
    getTestEnvironmentComponents
} = require("../../../lib/testHelpers.js");

const component = getTestEnvironmentComponents(componentName);


test("Checking array properties", () => {
  expect(Array.isArray(component)).toBe(true);
  expect(component).toHaveLength(2);
});

testHelpers.js内部,我有这个

module.exports = {
  getTestEnvironmentComponents: function (component) {
    const contents = require('.././components/'+component+'/tmp/test-manifest.json');
    return contents;
  },
  },
};

所以我有一个帮助脚本,该脚本希望在组件目录内有一个生成的JSON文件。

现在,我需要在每次测试之前针对每个组件生成该JSON文件。造成这一困难的原因是,每个组件的生成JSON文件的方法各不相同。当我对单个组件进行测试时,我只是向组件中添加了jest.config.js,如下所示:

module.exports = {
  globalSetup: "./test/0-setup.js",
  verbose: true,
};

然后为测试定义0-setup.js,如下所示:

// This file is the "globalSetup" file.
// FIXME: make this global somehow
module.exports = () => {
    const execa = require("execa");
    const fs = require("fs");
    const path = require("path");

    const command = "generate-json";
    const output = execa.shellSync(command);
    const testEnvironmentOutput = JSON.parse(output.stdout);

    if (!fs.existsSync("./tmp")) {
        fs.mkdirSync("./tmp");
    }

    fs.writeFileSync('./tmp/test-manifest.json', JSON.stringify(testEnvironmentOutput));
};

这适用于一个组件,但这意味着要运行我的jest测试,我必须进入每个组件并分别运行玩笑。

所以:

  • 是否可以在组件目录中定义安装任务?
  • 是否有更好的方法可以使我可以从根目录中运行jest,并且它将遍历子树并以其他方式运行设置任务?

1 个答案:

答案 0 :(得分:0)

听起来您需要在逐个测试的基础上进行大量工作,然后才能运行测试文件中的测试。

这听起来像是beforeAll的完美用法。

这是一个高度简化的示例:

const componentName = 'my_component';

let component;

beforeAll(async () => {
  doSomePrepWork();
  await doSomethingAsync();
  doSomeMorePrepWork();
  component = getTestEnvironmentComponents(componentName);
});

test("Checking array properties", () => {
  expect(Array.isArray(component)).toBe(true);
  expect(component).toHaveLength(2);
});

Jest将在测试的任何运行之前运行beforeAll,因此您可以使用它来为测试文件中的所有测试进行设置工作。

有用的注意事项:如果您需要在beforeAll中进行异步工作,则可以向其传递一个async函数(或向其传递一个返回{{1 }}),它将在允许Promise继续测试之前,先等待解决结果Promise