zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    Load Balancing 折半枚举大法好啊
    Big String 块状数组(或者说平方分割)
    K-th Number 线段树(归并树)+二分查找
    D. Powerful array 莫队算法或者说块状数组 其实都是有点优化的暴力
    CSU OJ PID=1514: Packs 超大背包问题,折半枚举+二分查找。
    运行时Runtime的API
    UIView的API
    UIControl的API
    UIScrollView的API
    使用KVO键值监听
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9274673.html
Copyright © 2011-2022 走看看