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

时间:2017-11-18 00:59:18

标签: javascript testing jest

我有几个有共同界面的类。我想写一个Jest测试套件并将其应用于所有类。理想情况下,它不应该混合在一个测试模块中,而是我希望将这个套件导入到每个类的每个单独的测试模块中。

有人可以请我指出一个类似这样的项目或提供一个例子吗?感谢。

1 个答案:

答案 0 :(得分:2)

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

提取的想法:

// shared_examples/index.js

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

exports.itBehavesLike = itBehavesLike;

&安培;

// aLiveBeing.js

const sharedSpecs = (args) => { 
  const target = args.target;

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

}

module.exports = sharedSpecs

&安培;

// Person.spec.js

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

describe("Person", () => {
  context("A Live Person", () => {
    const person = new Person({alive: true})
    const args = {target: person}
    itBehavesLike("aLiveBeing")(args)
  })
})
相关问题