Home > Enterprise >  Jest - Mock method of default class exported as named component of a package module
Jest - Mock method of default class exported as named component of a package module

Time:07-15

We have the below classes:

Component 1:

import React, { Component } from 'react'
import {foo} from 'blah'
import {bar} from 'blah-blah'

export default class Component1 extends Component {
  static propTypes = {
    ...
    ...
  }

  ...
  ...

  save() {
    doSomeOp()
  }

  render() {
    ...
    ...
  }
}

Component 2:

import React, { Component } from 'react'
import {foo} from 'blah'
import {bar} from 'blah-blah'

export default class Component2 extends Component {
  static propTypes = {
    ...
    ...
  }

  ...
  ...

  render() {
  }
}

Now, we have the following components within a package module - '@foo-bar/package'. The index.js for this package is as below:

index.js:

import Component1 from './src/component1'
import Component2 from './src/component2'
export { Component1, Component2 } 

This package is used in another component that I am trying to test. The code for this component is as below:

TestComponent:

import React from 'react'
import { Component1 } from '@foo-bar/package'

export function TestComponent(props) {
  ...
  ...

  return (
    <Component1 />   
  )
}

I have some logic in this TestComponent which triggers the save() method of Component1. What I intend to do is keep all the other properties of Component1 the same, but only mock the save() method. How could that be done? Thanks!

jest.mock('@foo-bar/package', () => {
  ???
})

CodePudding user response:

You can try:

import { Component1 } from '@foo-bar/package'

beforeAll(() => {
  jest.spyOn(Component1.prototype, 'save').mockImplementation(() => jest.fn())
})
  • Related