javascript - date.toLocaleString ('en-us' , { 日期样式 : 'long' }) not working in jest test but working in browser

标签 javascript reactjs jestjs

我不知道为什么这个功能测试没有通过,

export function timeStampToFormattedDate (timestamp) {
  if (!timestamp) return 'N/A'
  const date = new Date(timestamp)
  return date.toLocaleString('en-us', { dateStyle: 'long' })
}

测试

describe('timeStampToFormattedDate function', () => {
  it('returns formatted date string from last active user time-stamp', () => {
    const timeStamp = 1592810798024
    const formattedString = timeStampToFormattedDate(timeStamp)
    expect(formattedString).toEqual(`June 22, 2020`)
  })
})

我在运行测试时遇到此错误,

timeStampToFormattedDate function › returns formatted date string from last active user time-stamp

expect(received).toEqual(expected) // deep equality

Expected: "June 22, 2020"
Received: "6/22/2020, 10:26:38 AM"

   8 |     const timeStamp = 1592810798024
   9 |     const formattedString = timeStampToFormattedDate(timeStamp)
> 10 |     expect(formattedString).toEqual(`June 22, 2020`)
     |                             ^
  11 |   })
  12 |
  13 |   it('returns "N/A" if last active timestamp is null', () => {

  at Object.toEqual (src/utilities/dateTimeUtil.test.js:10:29)

当我通过在浏览器控制台中测试使用相同的参数调用来尝试该函数时,它按预期工作。

timeStampToFormattedDate(1592810798024)
"June 22, 2020"

那么为什么它会失败呢?

最佳答案

正如@James 在他们的评论中提到的,这仅在 Node V13.0.0 和更高版本中受支持,如下所述:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_compatibility

测试它的一种简单方法是从命令行运行它。输入 node 并复制粘贴您的方法,然后使用时间戳调用该方法。

这是一个例子:

enter image description here

关于javascript - date.toLocaleString ('en-us' , { 日期样式 : 'long' }) not working in jest test but working in browser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64162833/

相关文章:

testing - React 的 Jasmine 测试导致 Webpack 构建失败

javascript - 使用 TestUtils.Simulate 在输入元素上创建更改事件时遇到问题

javascript - 如何使用 jquery 为 div 中的每个元素设置边距?

javascript - 使用 javascript :history. go(-1) 有效,但我丢失了 css 属性和脚本

javascript - HTML5获取地理位置功能

javascript - 音量 slider 在单击时正确播放音频文件,但未更改同一元素的按键音量

reactjs - 类型 'RefObject<HTMLDivElement>' 的参数不可分配给类型 'IDivPosition' 的参数

javascript - 在 Jest 测试中将通用数据放在哪里

javascript - Jest 测试中 Express App 中的测试完成后无法记录问题

javascript - 从 document.getElementById 返回的 HTML 元素类型 String not Number