3

I have the following code where I want to mock moment() which doesn't take in any value thus capturing the date time now.
How do I mock this?

The following works but I find this to cumbersome thus looking to get it to work via jest.mock() which doesn't work for me.
Please see the example below.

This works but as said doesn't look like a clean approach. Do advice if this is the only way.

Created a folder named __ mocks __ inside my tests folder.
Within there, created a file named moment.js and the following is the content of moment.js

const moment = jest.requireActual('moment')
export default ((timestamp = 0) => {
    return moment(timestamp)
})

Looking to not have to create additional folder and files for every new mock types.
Thus attempted with the following but it doesn't seem to work.

The moment dates differ in snapshot.
If I pass in jest.requireActual('moment')(0) I end with the 1970 date and snapshot tries to match with actual date thus it is not mocking.
When I leave it blank as follows date ends up differing by milliseconds for the snapshot comparison. Again, not wocking.

test('some test', () => {

    jest.mock('moment', () => {
        return () => jest.requireActual('moment')()
    })

    const wrapper = shallow(<Custom/>)
    expect(wrapper).toMatchSnapshot()
})

This is the component being tested. (Condensed just to show the moment part)

class Custom extends Component {

    constructor(props) {
        super(props)

        this.state = {
            someTime: moment()
        }
    }

    render() {
        return (

            <p>{this.state.someTime}</p>
        )
    }
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
kar
  • 4,791
  • 12
  • 49
  • 74
  • 1
    You can adapt [this](https://stackoverflow.com/a/65130857/3001761) to moment - treat time as a dependency, and don't mock what you don't own. – jonrsharpe Dec 24 '20 at 12:58
  • Have a look at [How to mock moment.utc() for unit tests?](https://stackoverflow.com/q/46891897/4131048) and linked answers, maybe you can find something useful – VincenzoC Dec 28 '20 at 17:35

0 Answers0