我有一个时刻函数来格式化我从服务器获得的日期,以毫秒为单位。我正在尝试使用Enzyme和Jest进行测试,如果调用了moment function
(1),并且调用函数的输出是预期函数。
这是我的组件:
/* eslint-disable react/default-props-match-prop-types */
import React, { Fragment } from 'react';
import moment from 'moment';
import ILicense from 'user/dto/ILicense';
export interface Props {
license?: ILicense;
}
const LicenseInfo = <T extends object>({ license }: Props & T): JSX.Element => (
<Fragment>
<table className="table col-6 my-5">
<tbody>
<tr>
<td>Valid Until:</td>
<td className="font-weight-bold" id="expiry">
{moment(expiredAt).format('YYYY-MM-DD HH:mm:ssZZ')}
</td>
</tr>
</tbody>
</table>
</Fragment>
);
ComponentMoment.defaultProps = {
expiredAt: null,
};
export default ComponentMoment;
这是我的测试:
it('expect to show the expiration date if expiredAt is provided', () => {
const moment = jest.mock('moment', () => () => ({ format: () => '2019–02–28T23:59:58' }));
const license = {
expiredAt: 1551391198000,
};
const wrapper = mount<ComponentMoment>(<ComponentMoment license={license}>Test</ComponentMoment>);
wrapper.instance();
expect(moment).toHaveBeenCalled();
});
该测试目前失败了:
MatchError: Value must be a mock or a spy, and a huge object with various jest functions.
至于第二次测试,测试实际时间,我得到一个数字而不是字符串回来,而toString
,不工作。
我也读过这篇关于测试https://medium.com/front-end-weekly/mocking-moment-js-in-jest-a-simple-one-line-solution-61259ffaaa2
的时刻的文章,但我并没有真正理解它。
有人可以帮忙吗?我是新来测试..我非常沮丧,因为我没有理由,为什么它失败了。谢谢!!
正如我在评论中提到的,我相信您希望使用jest.fn()创建格式,然后将其附加到moment对象。