[Jest] Use property matchers in snapshot tests with Jest

With the right process in place, snapshot tests can be a great way to detect unintended changes in any part of your application that can be serialized. By grabbing a snapshot of your data in a known state, it takes a relatively small amount of code to check new output against your snapshot on each test run. When the output you want to test includes volatile data such as random number or dates, you end up updating your snapshot on every test run and your snapshot tests lose their value. Starting with Jest 23.0, the toMatchSnapshot method of expect allows you to define property matchers for specific keys in objects. Now we can specify that a value is of a certain type, while ignoring the specific value. In this lesson, we'll see an example of an object with non-deterministic values, and use property matchers in .toMatchSnapshot()to verify types while allowing for variation in those values.

 

复制代码
const { createPerson } = require('./index')

describe('createPerson', () => {
  it('Creates a person object', () => {
    const result = createPerson('John', 'Smith')
    expect(result).toMatchSnapshot({
      id: expect.any(String),
      createdAt: expect.any(Date)
    })
  })
})
复制代码

 

Then function 'createPreson' will genearte an object with random 'id' and 'createAt' time. When we usinig .toMatchSnapshot() for random value, it wil faild at second time.

To solve the problem, we can just check the type instead of actual value:

expect(result).toMatchSnapshot({
      id: expect.any(String),
      createdAt: expect.any(Date)
    })

It can make our test more flexable.

posted @   Zhentiw  阅读(165)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-07-06 [Canvas] Introduction to drawing with p5js
点击右上角即可分享
微信分享提示