mercredi 14 avril 2021

How do you mock a class within a class using Jest?

I'm trying to write some unit tests for a project and I'm have some difficulty completely mocking out a class. I can mock it out in within the scope of the test function, but I can't get it to mock out the class when it's being called in Class B below. Here's an example of what I have:

File1.ts

Class A {
 function x(){ return uuid()}
}
___mocks__/File1.ts

export const mockX = jest.fn().mockReturnValue('x');

const mock = jest.fn().mockImplementation(() => {
    return { x: mockX};
});

export default mock;
File2.ts

//...imports...

Class B {
 function y(){
  //...lots of code that does stuff
   let serialNum = A.x();
   return {serialNum:serialNum, ...other important values}
  }
}
File2.test.ts

//...imports....
import {mockX} from '___mocks__/File1';

describe('test',()=>{

test('',()=>{
     jest.mock('/path/to/file1');
     const A = require('/path/to/file1');
     A.x = mockX;

      let w = A.x(); 
      console.log(w) // will be 'x'  
      let expectedResult = {serialNum: w, ...other important values}
     
      let z = B.y();
      console.log(z) // will be an object that has a regular uuid {serialNum: f5c5d215-8efb-44a0-8743-1252106ad77}
     expect(z).toStrictlyEqual(expectedResult);


  });

});

In essence my problem is that I'm dealing with random UUIDs in my tests and I'm not sure how to write a sufficient test case. I'd like to mock out the class that's generating the UUID for both the received and expected results.

Aucun commentaire:

Enregistrer un commentaire