【问题标题】:Jest | Test if moment function has been called and if the return output is the correct one开玩笑 |测试是否调用了矩函数以及返回输出是否正确
【发布时间】:2019-07-16 07:32:46
【问题描述】:

我有一个矩函数来格式化从服务器获取的日期(以毫秒为单位)。我正在尝试使用 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 的文章,但我真的不明白。

有人可以帮忙吗?我是测试新手..我非常沮丧,因为我不明白为什么它失败了。谢谢!!

【问题讨论】:

  • 嘿迪米特里斯。我知道这不是您问题的答案,但是您提到了测试新手,我想我会给您一些建议……作为一般规则,您不应该测试框架代码。信任时刻来测试时刻......你没有自己的逻辑可以在那里测试。
  • 谢谢。说实话,我自己也是这么想的。在过去的一周里,我发现自己经常处于这种情况。我得到第二个测试场景是暂时的,但是如果调用函数,是组件本身的逻辑,还是我错了?
  • 你的 mock 中有多余的 () => 吗?
  • 是的,我有,但这不是问题。错误是这样的:MatchError: Recieved Value must be a mock or a spy
  • 哦。我很确定您希望格式为格式:jest.fn()

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

正如我在 cmets 中提到的,我相信您希望使用 jest.fn() 创建格式,然后将其附加到 moment 对象。

https://jestjs.io/docs/en/expect.html#tohavebeencalled

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2019-04-18
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多