Skip to contents

Discover and execute test files (test-*.R and test-*.md) for a package. Tests are run inside the package namespace, so you can call internal (non-exported) functions directly without the ::: operator.

Usage

test_pkg(package = pkg_name(), dir = NULL, filter = NULL, update = NA)

Arguments

package

The package name. By default, it is detected from the DESCRIPTION file.

dir

The directory containing test files. If NULL (the default), testit/ or tests/testit/ under the current working directory is used (whichever exists). You can also pass a custom path.

filter

An optional regular expression to select a subset of test files. Only files whose names match the pattern will be run. For example, filter = "plot" runs only test files with "plot" in their names.

update

Controls snapshot file behavior:

  • TRUE: always update snapshot files with actual output (never errors).

  • NA (default): update only if the file is tracked by Git (so you can review diffs before accepting).

  • FALSE: never update; always compare and error on mismatch.

Value

Invisible NULL. If any tests fail, a single error is thrown at the end with all failure messages combined.

Details

Test files are looked up in the testit/ or tests/testit/ directory by default. Files must be named test-*.R for regular tests or test-*.md for snapshot tests. Other files in the directory are ignored (but you can source() them from your tests if needed).

Helper files named helper*.R (e.g., helper.R, helper-utils.R) are sourced before any test file runs. Objects defined in helpers are available to all tests. Global helpers in the parent directory (e.g., tests/helper.R) are sourced first, followed by helpers in the test subdirectory itself. This allows you to share common utilities across all test subdirectories.

Each test file runs in a clean environment (previous test objects are removed), and the working directory is set to the directory containing the test file.

See https://pkg.yihui.org/testit/#sec:snapshot-testing for more details about snapshot testing.

Note

You must call library(testit) before test_pkg(). Test scripts use assert() and other testit functions without the testit:: prefix, so the package needs to be on the search path. Without library(testit), you will get "could not find function" errors.

All test scripts must be encoded in UTF-8 if they contain multibyte characters.

When filter or update are not explicitly provided, test_pkg() checks commandArgs(TRUE) for command-line arguments: --filter=PATTERN sets the filter, and --update sets update = TRUE. This allows you to pass these options via Rscript tests/*.R --filter=PATTERN --update without modifying individual test_pkg() calls.

Examples

if (FALSE) { # \dontrun{
library(testit)
test_pkg('testit')
} # }