我使用Moment timeZone.js出现了一个错误。它在网页上完美运行,但是当我尝试实现测试时,测试结果总是返回下面的错误。
这是我在网页上使用的代码:
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>
)
}
}
这是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;
这是我在测试文件上使用的代码
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();
});
});
这是包装的版本:
"moment": "~2.18.1",
"moment-timezone": "~0.5.13",
这是错误消息:
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>
可能会迟到一些,但为了他人的利益。我们之所以得到这个,是因为Mists timezone期望从当时的包装中获得一个版本号。
如瞬间Zone.js
所示
var momentVersion = moment.version.split('.'),
major = +momentVersion[0],
minor = +momentVersion[1];
开玩笑时,它试图嘲笑您包含的所有内容,因此时刻被嘲笑了。由于属性被排除在外,因此仅在功能上被模拟,您将不得不取消 moment
和 moment-timezone
或将伪造的版本编号包含在模拟的moment
对象中。
我遇到了同样的问题;这是我嘲笑时刻的一个例子:
let diffMins = updateThreshold + 1;
jest.mock('moment', () => {
const mMoment = {
diff: jest.fn(() => diffMins),
};
const fn = jest.fn(() => mMoment);
fn.version = '2.24';
fn.tz = jest.fn();
fn.fn = jest.fn();
return fn;
});