dimanche 21 février 2021

Mock JSON file consumed by the constructor of a class with Jest

The constructor function of my class is consuming an imported JSON file. I need to mock this file and use another JSON file that has data for testing purposes only.

// myClass.ts
import * as myData from '../data.json;

export class MyClass {
  constructor() {
    this.data = [...myData];
  }

  getData() {
    return this.data;
  }
}
// myClass.test.ts
import { MyClass } from '../myClass.ts;
import * as myTestData from '../__mocks__/data.json;

describe('MyClass', () => {
  let myClass: MyClass;

  beforeEach(() => {
     myClass = new MyClass();

  // How can I modify the constructor so when I instantiate MyClass,
// it uses myTestData instead of the real data json file? 
  })
 

  
  ...
})

Any idea how to achieve this using Jest?

Aucun commentaire:

Enregistrer un commentaire