如何使用Jest实现共享测试用例?

Dmi*_*nov 5 javascript testing jest

我有几个具有通用接口的类。我想一次编写一个Jest测试套件,并将其应用于所有类。理想情况下,不应将其混入一个测试模块中,相反,我希望将此套件导入到每个类的每个单独的测试模块中。

有人可以指出一个完成此类工作的项目或提供示例吗?谢谢。

thi*_*ign 7

我发现这篇文章可能会有所帮助:https : //medium.com/@walreyes/sharing-specs-in-jest-82864d4d5f9e

提取的想法:

// shared_examples/index.js

const itBehavesLike = (sharedExampleName, args) => {
  require(`./${sharedExampleName}`)(args);
};

exports.itBehavesLike = itBehavesLike;
Run Code Online (Sandbox Code Playgroud)

&

// aLiveBeing.js

const sharedSpecs = (args) => { 
  const target = args.target;
  
  describe("a Live Being", () => {
    it("should be alive", () => {
     expect(target.alive).toBeTruthy();
    })
  })  
  
}

module.exports = sharedSpecs
Run Code Online (Sandbox Code Playgroud)

&

// Person.spec.js

const { itBehavesLike} = require('shared_examples');

describe("Person", () => {
  describe("A Live Person", () => {
    const person = new Person({alive: true})
    const args = {target: person}
    itBehavesLike("aLiveBeing")(args)
  })
})
Run Code Online (Sandbox Code Playgroud)