0

I'm trying to mock a function which is called inside my react component. Here is an exemple, with the function getContent(). How could I set my own return value in the test ?

Component.test.tsx :

describe('TEST', () => {
 it('test', () => {
  ...
  expect.assertions(1);
  renderer = render(<MyComponent></MyComponent>)
  expect(renderer.toContain('myValue')) 
  }
)}

MyComponent.tsx :

export const MyComponent = (props) => {
 const externalClass = new classFromAnotherFile()
 const content = externalClass.getContent()
  return (
    <View>
     content={content}
    </View>
}

AnotherFile.tsx

export class classFromAnotherFile {
 constructor(...){}
 getContent(): string { ... }
}

user676767
  • 41
  • 5
  • 1
    _Are_ you trying to do that? There's nothing in the test related to mocking. When you `new` up collaborators like that you _couple_ your code to them, so it's probably not appropriate to use a test double to replace it - this would be easier to test with a less tightly coupled design. Also you know `{props}` isn't passing props (other than `children`) to the component, right? – jonrsharpe May 15 '22 at 22:05
  • Thet getContent() function comes from a ViewModel, so that the logic and component are fully decoupled. For the second part, you're right, I edited the post, thanks – user676767 May 15 '22 at 22:12
  • They're _not_ decoupled, because you have `new classFromAnotherFile()` in your component. Jest _can_ mock imports, you can research how to do that, but without more context it's hard to say whether that's actually the right solution. – jonrsharpe May 15 '22 at 22:13
  • Thank you for the remark regarding the architecture, but here it's not my question (I know the XY problem etc.) I have to do a hotfix here, so I will not modify the whole structure. I'm just asking if it's possible to mock the method since it's constructed in the "MyComponent.tsx" and not in the "Component.test.tsx" ? I already test, seems to not work. – user676767 May 16 '22 at 08:55

1 Answers1

2

Just find the solution, from all the solutions in the documentation, the last one was the good one :

const getContentMock = jest
  .spyOn(YourClass.prototype, 'getContent')
  .mockImplementation(() => {
    console.log('mocked function');
  });
user676767
  • 41
  • 5