Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement shared test cases using Jest?

I have few classes that have common interface. I would want to write a Jest test suite once and apply it to all the classes. Ideally it should not be mixed up in one test module, instead I expect this suite to be imported to each individual test module for each class.

Could someone please point me out to a project where something like this is done or provide an example? Thanks.

like image 830
Dmitry Druganov Avatar asked Nov 18 '17 00:11

Dmitry Druganov


1 Answers

I found this article that might be helpful: https://medium.com/@walreyes/sharing-specs-in-jest-82864d4d5f9e

The idea extracted:

// 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", () => {
  describe("A Live Person", () => {
    const person = new Person({alive: true})
    const args = {target: person}
    itBehavesLike("aLiveBeing")(args)
  })
})
like image 170
thisismydesign Avatar answered Sep 21 '22 13:09

thisismydesign