首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嘲笑模拟时刻()返回特定日期

嘲笑模拟时刻()返回特定日期
EN

Stack Overflow用户
提问于 2021-07-01 11:05:03
回答 2查看 3.4K关注 0票数 2

我知道这个问题已经问过好几次了。

但我找不到适合我的案子。

我想嘲笑一下()返回一个特定日期的时刻。

First,我嘲笑

代码语言:javascript
复制
jest.mock("moment", () => {
  return (date: string) =>
    jest.requireActual("moment")(date || "2021-01-01T00:00:00.000Z");
});

但是我使用了矩的一些属性(例如moment.duration()...),所以当模拟像这样的时候,它就不能工作了。

Next我尝试通过几种方式来模拟Date.now

代码语言:javascript
复制
jest.spyOn(Date, "now").mockReturnValue(+new Date("2021-01-01T00:00:00.000Z"));
代码语言:javascript
复制
Date.now = jest.fn(() => +new Date("2021-01-01T00:00:00.000Z")

但是在执行此操作时,当调用moment()时,它返回一个无效的日期。

我不知道我做错了什么。

EN

回答 2

Stack Overflow用户

发布于 2021-07-01 13:12:35

模拟moment()函数及其返回的值。使用jest.requireActual('moment')获取原始模块。将其属性和方法复制到模拟的属性和方法。

例如。

index.js

代码语言:javascript
复制
import moment from 'moment';

export function main() {
  const date = moment().format();
  console.log('date: ', date);
  const duration = moment.duration(2, 'minutes').humanize();
  console.log('duration: ', duration);
}

index.test.js

代码语言:javascript
复制
import { main } from '.';
import moment from 'moment';

jest.mock('moment', () => {
  const oMoment = jest.requireActual('moment');
  const mm = {
    format: jest.fn(),
  };
  const mMoment = jest.fn(() => mm);
  for (let prop in oMoment) {
    mMoment[prop] = oMoment[prop];
  }
  return mMoment;
});

describe('68209029', () => {
  it('should pass', () => {
    moment().format.mockReturnValueOnce('2021-01-01T00:00:00.000Z');
    main();
  });
});

测试结果:

代码语言:javascript
复制
 PASS  examples/68209029/index.test.js (8.914 s)
  68209029
    ✓ should pass (20 ms)

  console.log
    date:  2021-01-01T00:00:00.000Z

      at Object.main (examples/68209029/index.js:5:11)

  console.log
    duration:  2 minutes

      at Object.main (examples/68209029/index.js:7:11)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.726 s

看看日志,我们正确地模拟了moment().format()的返回值,并继续使用moment.duration(2, 'minutes').humanize()方法的原始实现。

票数 3
EN

Stack Overflow用户

发布于 2021-07-05 03:35:48

除了@幻灯片2的答案之外。

我只想为这个添加另一种方式:

代码语言:javascript
复制
jest.mock("moment", () => {
  // Require actual moment
  const actualMoment = jest.requireActual("moment");

  // Mocking moment func: 
  // moment() => return specific date, and it won't affect moment(date) with param.
  const mockMoment: any = (date: string | undefined) =>
    actualMoment(date || "2021-01-01T00:00:00.000Z");

  // Now assign all properties from actual moment to the mock moment, so that they can be used normally
  for (let prop in actualMoment) {
    mockMoment[prop] = actualMoment[prop];
  }
  return mockMoment;
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68209029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档