1

Say I have something like this

index.js:

import React, { Component } from 'react';
import Button from './Button';

export class Item extends Component {
  render() {
    return <div>{this.props.state.item}</div>;
  }
}

export class Modal extends Component {
  render() {
    return (
      <div class="modal">
        <Item url="www.stackoverflow.com/" />
        <Button>Great</Button>
      </div>
    );
  }
}


// Redux stuff
// export default connect(...)

and I then wish to just test the Modal and mock the Item

I have tried something like

// index.test.js
const Modal = jest.mock("Modal", () => {
  const ModalToTest = require.requireActual("./index.js")
  return ({
    Modal: ModalToTest,
    Item: jest.fn(() => null)
  })
})

But it don't work..


Bonus info: I'm using named export in order to test the component without redux

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Norfeldt
  • 8,272
  • 23
  • 96
  • 152
  • How jest.mock performs is; first you need to import your real module with alias or relative path. Then you need to use jest.mock(, implementation); – Tugay İlik Sep 19 '19 at 09:48
  • So if `index.test.js` then `const Modal = jest.mock("./", () => {...` it should work? or do I have to do `import { Modal, Item as ItemMock } from `./` and then do `jest.mock('./', () =>
    )` - how do I specify it to `ItemMock`?
    – Norfeldt Sep 19 '19 at 11:05
  • I didn't have a chance to give a try but, `import { Modal, Item as ItemMock }` completely imports your index.js and gives you Modal and Item as seperate modules. So what you have to do is, `jest.mock('./', () => { return { ItemMock: jest.fn(), Modal: jest.fn(), } })` – Tugay İlik Sep 19 '19 at 11:25
  • @Tugayİlik tried your suggest (and a lot of other things) - but no luck so far... – Norfeldt Sep 19 '19 at 12:27

0 Answers0