Skip to content

Add snapshot testing support  #178

@adamgen

Description

@adamgen

Coming from a difference discipline, I enjoy very much snapshot testing both in js and python.

Motivation

When writing snapshot tests you do not need to manually maintain expected values. This is useful specially when dealing with long or complicated string that you basically copy paste from the error to the expected variable.

Proposed new API

Snapshots have to accept a test name which will be used as the file name.

snapshot "database" "$(bash def2.sh --database=mydb)"

To update snapshots pass down a --snapshot-update argument.

Implementation

This snapshot function works good for me


snapshot() {
  mkdir -p snapshots
  local FILE_NAME="$1"
  local EXPECTED="$2"
  local FILE_PATH
  local FILE_CONTENTS

  FILE_PATH="snapshots/$FILE_NAME"

  if [ -f "$FILE_PATH" ]; then
    FILE_CONTENTS=$(cat "$FILE_PATH")
    if [ "$EXPECTED" = "$FILE_CONTENTS" ]; then
      _shunit_assertPass
    else
      if [ "$SNAPSHOT_UPDATE" = "true" ]; then
        echo "$EXPECTED" >"$FILE_PATH"
        fail "Snapshot $FILE_NAME updated, re-run to check"
      else
        failNotEquals "$FILE_NAME" "$FILE_CONTENTS" "$EXPECTED"
      fi
    fi
  else
    echo "$EXPECTED" >"$FILE_PATH"
    fail "Snapshot $FILE_NAME created, re-run to check"
  fi
}

To support the --snapshot-update flag I simply added this to my script

SNAPSHOT_UPDATE=""
TEST_ARGS=""

while [ $# -gt 0 ]; do
  case $1 in
  -u | --snapshot-update)
    SNAPSHOT_UPDATE="true"
    shift
    ;;
  esac
  TEST_ARGS="$TEST_ARGS $1"
  shift
done

# tests here...

. ./shunit2 ${TEST_ARGS}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions