[英]Mock a class function used inside a React component
I'm trying to mock a function which is called inside my react component.我正在尝试模拟一个在我的反应组件中调用的函数。 Here is an exemple, with the function getContent().
这是一个示例,带有函数 getContent()。 How could I set my own return value in the test ?
如何在测试中设置自己的返回值?
Component.test.tsx :组件.test.tsx:
describe('TEST', () => {
it('test', () => {
...
expect.assertions(1);
renderer = render(<MyComponent></MyComponent>)
expect(renderer.toContain('myValue'))
}
)}
MyComponent.tsx : MyComponent.tsx :
export const MyComponent = (props) => {
const externalClass = new classFromAnotherFile()
const content = externalClass.getContent()
return (
<View>
content={content}
</View>
}
AnotherFile.tsx另一个文件.tsx
export class classFromAnotherFile {
constructor(...){}
getContent(): string { ... }
}
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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.