Javascript 单元测试具有非常相似测试场景的多个功能的最佳实践是什么?

Javascript 单元测试具有非常相似测试场景的多个功能的最佳实践是什么?,javascript,node.js,unit-testing,testing,mocha.js,Javascript,Node.js,Unit Testing,Testing,Mocha.js,假设我有两个纯函数,pureFn1和pureFn2。这些功能必须通过类似的测试 describe("generic function", () => { it("should fulfill condition 1", testCondition1); it("should fulfill condition 2", testCondition2); it("should fulfill condition 3", testCondition3); it("shoul

假设我有两个纯函数,
pureFn1
pureFn2
。这些功能必须通过类似的测试

describe("generic function", () => {
  it("should fulfill condition 1", testCondition1);

  it("should fulfill condition 2", testCondition2);

  it("should fulfill condition 3", testCondition3);

  it("should fulfill condition 4", testCondition4);
});
如何为这些函数编写类似的测试?测试套件应该是可重用的吗

例如,如果我们重新使用测试套件,它最终将如下所示:

const reusableTestSuite = (codeUnderTest) => {
  describe(`${codeUnderTest.name}`, () => {
    it("should fulfill condition 1", testCondition1(codeUnderTest));

    it("should fulfill condition 2", testCondition2(codeUnderTest));

    it("should fulfill condition 3", testCondition3(codeUnderTest));

    it("should fulfill condition 4", testCondition4(codeUnderTest));
  });
};

reusableTestSuite(pureFn1);
reusableTestSuite(pureFn2);
这是相当枯燥的,但问题是有一个抽象,它可能使测试更难阅读和修改,因此可能会阻止开发人员以速度和易用性的名义编写更多的测试。本文第8点对此进行了讨论。当这些抽象测试中断时,下一个开发人员可能不喜欢阅读它

另一个选项是复制粘贴测试:

describe("pureFn1", () => {
  it("should fulfill condition 1", testCondition1Fn1);

  it("should fulfill condition 2", testCondition2Fn1);

  it("should fulfill condition 3", testCondition3Fn1);

  it("should fulfill condition 4", testCondition4Fn1);
});

describe("pureFn2", () => {
  it("should fulfill condition 1", testCondition1Fn2);

  it("should fulfill condition 2", testCondition2Fn2);

  it("should fulfill condition 3", testCondition3Fn2);

  it("should fulfill condition 4", testCondition4Fn2);
});
这完全是代码重复。没有抽象。如果我们有两个函数,它们之间有20个公共属性,那么我们将不得不复制并粘贴20个测试,并记住在其中一个测试发生更改时,永远更新所有类似的测试

那么,在这些方法之间,哪种方法更好?或者有没有第三种方法,一种编写单元测试的最佳实践,可以让我们从抽象中获得好处,同时不会让下一个开发人员很难立即了解出了什么问题,从而不会阻止他们编写更多的单元测试