首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用luxon DateTime进行测试

使用luxon DateTime进行测试
EN

Stack Overflow用户
提问于 2021-08-08 07:26:20
回答 1查看 472关注 0票数 0

我想使用Luxon测试以下内容:

代码语言:javascript
复制
import { DateTime } from 'luxon'

export const calculateAge = (birthDate: DateTime) => {
  let dateDifference = Math.abs(birthDate.diffNow('years').years)
  if (dateDifference < 1) {
    dateDifference = Math.abs(birthDate.diffNow('months').months)
  }

  return String(Math.floor(dateDifference))
}

我刚开始使用React Native并使用Jest进行测试,但到目前为止,我测试的'it‘块看起来像这样:

代码语言:javascript
复制
  it('calls the calculates age function', () => {
    jest.spyOn(calculateAge, calculateAge('1950-02-02'))

    expect(calculateAge).toHaveBeenCalled()
  })

我得到以下错误:

TypeError: birthDate.diffNow is not a function

有人知道我怎么测试这个吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-08 08:36:06

您通常只需要监视传递的回调,以检查它们是否被实际调用。在这里,您正在测试一个函数,因此您肯定不想模拟或监视它。

代码语言:javascript
复制
export const calculateAge = (birthDate: DateTime) => {
  let dateDifference = Math.abs(birthDate.diffNow('years').years)
  if (dateDifference < 1) {
    dateDifference = Math.abs(birthDate.diffNow('months').months)
  }

  return String(Math.floor(dateDifference))
}

关于TypeError: birthDate.diffNow is not a function错误,这是因为calculateAge需要一个Luxon DateTime对象,而您正在传递一个String对象。

对于测试,您需要模拟javascript日期/时间,以便可以可靠地与测试中的静态日期进行比较,否则每次测试运行时,now时间总是不同的。

代码语言:javascript
复制
import { advanceTo, clear } from 'jest-date-mock';

...

afterAll(() => {
  clear(); // clear jest date mock
});

it('should compute diff in years', () => {
  // Set "now" time
  advanceTo(DateTime.fromISO('2021-08-08T01:20:13-0700').toJSDate());

  expect(calculateAge(DateTime.fromISO('2020-08-07T00:00:00-0700'))).toEqual('1');
});

it('should compute diff in months', () => {
  // Set "now" time
  advanceTo(DateTime.fromISO('2021-08-08T01:20:13-0700').toJSDate());

  expect(calculateAge(DateTime.fromISO('2020-08-09T00:00:00-0700'))).toEqual('11');
});

您可以想到其他有趣的测试/边界情况。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68698633

复制
相关文章

相似问题

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