I got an error using moment-timezone.js. It runs perfectly on a web page, but when I try to implement the test for it, the test result always returns an error like below.
This is the code I use on the web page:
import moment from 'moment-timezone';
class TimezoneCityItem extends React.Component {
componentDidMount(){
this.setState({
time: moment.tz(this.props.timezone)
})
}
render(){
return (
<div>{this.state.time.format('HH:mm')}</div>
)
}
}
This is timezoneListDummyData
:
const timezoneList = [
{ name: 'los-angeles', title: 'Los Angeles', timezone: 'America/Los_Angeles' },
{ name: 'washington', title: 'Washington', timezone: 'America/New_York' },
{ name: 'london', title: 'London', timezone: 'Europe/London' },
{ name: 'dubai', title: 'Dubai', timezone: 'Asia/Dubai' },
{ name: 'hongkong', title: 'Hongkong', timezone: 'Asia/Hong_Kong' },
];
export default timezoneList;
this is code I use on my test file
import React from 'react';
import { shallow } from 'enzyme';
import TimezoneCityItem from '../TimezoneCity.item';
import timezoneList from '/lib/timezoneListDummyData'; // It just an array list of timezone
describe('<TimezoneCityItem />', () => {
test('Should render TimezoneCityItem correctly', () => {
const wrapper = shallow(<TimezoneCityItem {...timezoneList[0]} />);
expect(wrapper).toMatchSnapshot();
});
});
This is the version of the packages:
"moment": "~2.18.1",
"moment-timezone": "~0.5.13",
This is the error message:
Test suite failed to run
TypeError: Cannot read property 'split' of undefined
at node_modules/moment-timezone/moment-timezone.js:36:34
at Object.<anonymous>.moment (node_modules/moment-timezone/moment-timezone.js:14:20)
at Object.<anonymous> (node_modules/moment-timezone/moment-timezone.js:18:2)
at Object.<anonymous> (node_modules/moment-timezone/index.js:1:120)
at Object.<anonymous> (imports/ui/components/mainLayout/TimezoneCity.item.jsx:3:49)
at Object.<anonymous> (imports/ui/components/mainLayout/TimezoneCity.jsx:3:47)
at Object.<anonymous> (imports/ui/components/mainLayout/MainLayout.jsx:6:47)
at Object.<anonymous> (imports/ui/components/mainLayout/__tests__/MainLayout.test.js:3:19)
at Generator.next (<anonymous>)
at new Promise (<anonymous>)
at Generator.next (<anonymous>)
at <anonymous>
probably a little late for this, but for the benefit of others. The reason why we are getting this because moment-timezone expects a version number from the moment package.
As seen at moment-timezone.js
var momentVersion = moment.version.split('.'),
major = +momentVersion[0],
minor = +momentVersion[1];
When you run jest, it tries to mock everything that you include, therefore moment is getting mocked. Since attributes are excluded, on only functions are mocked, you will either have to unmock moment
and moment-timezone
or include a fake version number to the mocked moment
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With