Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add snapshot testing support #178

Open
adamgen opened this issue May 20, 2024 · 0 comments
Open

Add snapshot testing support #178

adamgen opened this issue May 20, 2024 · 0 comments

Comments

@adamgen
Copy link

adamgen commented May 20, 2024

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}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant