test-shiny-app
정보
이 스킬은 개발자가 Shiny 애플리케이션을 테스트하는 데 도움을 줍니다. shinytest2를 사용한 엔드투엔드 브라우저 테스트와 testServer()를 활용한 서버 로직 단위 테스트를 다룹니다. 스냅샷 테스트, CI 통합, 외부 서비스 모킹에 대한 내용을 포함합니다. 기존 앱에 테스트를 추가할 때, 새 프로젝트의 테스트 환경을 설정할 때, 회귀 테스트를 작성할 때, 또는 CI/CD 파이프라인에 테스트를 통합할 때 사용하세요.
빠른 설치
Claude Code
추천npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/test-shiny-appClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Test Shiny App
Set up comprehensive testing for Shiny applications using shinytest2 (end-to-end) and testServer() (unit tests).
When Use
- Add tests to existing Shiny application
- Set up testing strategy for new Shiny project
- Write regression tests before refactoring Shiny code
- Integrate Shiny app tests into CI/CD pipelines
Inputs
- Required: Path to Shiny application
- Required: Test scope (unit tests, end-to-end, or both)
- Optional: Whether to use snapshot testing (default: yes for e2e)
- Optional: CI platform (GitHub Actions, GitLab CI)
- Optional: Modules to test in isolation
Steps
Step 1: Install Testing Dependencies
install.packages("shinytest2")
# For golem apps, add as a Suggests dependency
usethis::use_package("shinytest2", type = "Suggests")
# Set up testthat infrastructure if not present
usethis::use_testthat(edition = 3)
Got: shinytest2 installed, testthat directory structure in place.
If fail: shinytest2 needs chromote (headless Chrome). Install Chrome/Chromium on system. WSL: sudo apt install -y chromium-browser. Verify with chromote::find_chrome().
Step 2: Write testServer() Unit Tests for Modules
Create tests/testthat/test-mod_dashboard.R:
test_that("dashboard module filters data correctly", {
testServer(dataFilterServer, args = list(
data = reactive(iris),
columns = c("Species", "Sepal.Length")
), {
# Set inputs
session$setInputs(column = "Species")
session$setInputs(value_select = "setosa")
session$setInputs(apply = 1)
# Check output
result <- filtered()
expect_equal(nrow(result), 50)
expect_true(all(result$Species == "setosa"))
})
})
test_that("dashboard module handles empty data", {
testServer(dataFilterServer, args = list(
data = reactive(iris[0, ]),
columns = c("Species")
), {
# Module should not error on empty data
expect_no_error(session$setInputs(column = "Species"))
})
})
Key patterns:
testServer()tests module server logic without a browser- Pass reactive arguments via the
argslist - Use
session$setInputs()to simulate user interactions - Access reactive return values directly by name
- Test edge cases: empty data, NULL inputs, invalid values
Got: Module tests pass with devtools::test().
If fail: testServer() errors with "not a module server function"? Ensure function uses moduleServer() internally. session$setInputs() doesn't trigger reactives? Add session$flushReact() after setting inputs.
Step 3: Write shinytest2 End-to-End Tests
Create tests/testthat/test-app-e2e.R:
test_that("app loads and displays initial state", {
# For golem apps
app <- AppDriver$new(
app_dir = system.file(package = "myapp"),
name = "initial-load",
height = 800,
width = 1200
)
on.exit(app$stop(), add = TRUE)
# Wait for app to load
app$wait_for_idle(timeout = 10000)
# Check that key elements exist
app$expect_values()
})
test_that("filter interaction updates the table", {
app <- AppDriver$new(
app_dir = system.file(package = "myapp"),
name = "filter-interaction"
)
on.exit(app$stop(), add = TRUE)
# Interact with the app
app$set_inputs(`filter1-column` = "cyl")
app$wait_for_idle()
app$set_inputs(`filter1-apply` = "click")
app$wait_for_idle()
# Snapshot the output values
app$expect_values(output = "table")
})
Key patterns:
AppDriver$new()launches the app in headless Chrome- Always use
on.exit(app$stop())to clean up - Module input IDs use the format
"moduleId-inputId" app$expect_values()creates/compares snapshot filesapp$wait_for_idle()ensures reactive updates complete
Got: End-to-end tests create snapshot files in tests/testthat/_snaps/.
If fail: Chrome not found? Set CHROMOTE_CHROME environment variable to Chrome binary path. Snapshots fail on CI but pass local? Check for platform-dependent rendering differences — use app$expect_values() for data snapshots rather than app$expect_screenshot() for visual ones.
Step 4: Record Test Interactively (Optional)
shinytest2::record_test("path/to/app")
This opens the app in a browser with a recording panel. Interact with the app, then click "Save test" to auto-generate test code.
Got: Test file generated in tests/testthat/ with recorded interactions.
If fail: Recorder doesn't open? Check app runs successful with shiny::runApp() first. Recorder needs working app.
Step 5: Set Up Snapshot Management
For snapshot-based tests, manage expected values:
# Accept new/changed snapshots after review
testthat::snapshot_accept("test-app-e2e")
# Review snapshot differences
testthat::snapshot_review("test-app-e2e")
Add snapshot directories to version control:
tests/testthat/_snaps/ # Committed — contains expected values
Got: Snapshot files tracked in git for regression detection.
If fail: Snapshots change unexpected? Run testthat::snapshot_review() to see diffs. Accept intentional changes with testthat::snapshot_accept().
Step 6: Integrate with CI
Add to .github/workflows/R-CMD-check.yaml or create a dedicated workflow:
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y chromium-browser
- name: Set Chrome path
run: echo "CHROMOTE_CHROME=$(which chromium-browser)" >> $GITHUB_ENV
- name: Run tests
run: |
Rscript -e 'devtools::test()'
For golem apps, ensure the app package is installed before testing:
- name: Install app package
run: Rscript -e 'devtools::install()'
Got: Tests pass in CI with headless Chrome.
If fail: Common CI issues: Chrome not installed (add apt-get step), display server missing (shinytest2 uses headless mode default so usually not issue), or timeout on slow runners (increase timeout in AppDriver$new()).
Checks
-
devtools::test()runs all tests without errors - testServer() tests cover module server logic
- shinytest2 tests cover key user workflows
- Snapshot files committed to version control
- Tests pass in CI environment
- Edge cases tested (empty data, NULL inputs, error states)
Pitfalls
- Test UI rendering instead of logic: Prefer
testServer()for logic andapp$expect_values()for data. Only useapp$expect_screenshot()when visual appearance matters — screenshots brittle across platforms. - Module ID format in e2e tests: Setting module inputs via AppDriver? Use
"moduleId-inputId"format (hyphen-separated), not"moduleId.inputId". - Flaky timing: Always call
app$wait_for_idle()afterapp$set_inputs(). Without it, assertions may run before reactive updates complete. - Snapshot drift: Never commit snapshots generated on different platforms (Mac vs Linux). Standardize on CI platform for snapshot generation.
- Missing Chrome on CI: shinytest2 needs Chrome/Chromium. Always include installation step in CI workflows.
See Also
build-shiny-module— create testable modules with clear interfacesscaffold-shiny-app— set up app structure with testing infrastructurewrite-testthat-tests— general testthat patterns for R packagessetup-github-actions-ci— CI/CD setup for R packages (golem apps)
GitHub 저장소
연관 스킬
evaluating-llms-harness
테스팅이 Claude Skill은 MMLU, GSM8K를 포함한 60개 이상의 표준화된 학술 과제에서 LLM 성능을 벤치마크하기 위해 lm-evaluation-harness를 실행합니다. 개발자들이 모델 품질을 비교하고, 학습 진행 상황을 추적하거나 학술 결과를 보고할 수 있도록 설계되었습니다. 이 도구는 HuggingFace와 vLLM 모델을 포함한 다양한 백엔드를 지원합니다.
cloudflare-cron-triggers
테스팅이 스킬은 cron 표현식을 사용하여 Worker를 스케줄링하기 위한 Cloudflare Cron Triggers 구현에 관한 포괄적인 지식을 제공합니다. 주기적 작업, 유지보수 작업, 자동화된 워크플로우 설정 방법을 다루며, 잘못된 cron 표현식이나 시간대 문제 같은 일반적인 이슈들을 해결하는 방법을 포함합니다. 개발자들은 이를 통해 스케줄된 핸들러 구성, cron 트리거 테스트, Workflows 및 Green Compute와의 연동 작업을 수행할 수 있습니다.
webapp-testing
테스팅이 Claude Skill은 Python 스크립트를 통해 로컬 웹 애플리케이션을 테스트하기 위한 Playwright 기반 툴킷을 제공합니다. 프론트엔드 검증, UI 디버깅, 스크린샷 캡처, 로그 확인 기능을 지원하며 서버 라이프사이클을 관리합니다. 브라우저 자동화 작업에 사용하되 컨텍스트 오염을 방지하기 위해 소스 코드를 읽지 않고 스크립트를 직접 실행하세요.
finishing-a-development-branch
테스팅이 스킬은 테스트 통과를 확인한 후 체계적인 통합 옵션을 제시하여 개발자가 완성된 작업을 마무리하도록 돕습니다. 구현이 완료된 후 머지, PR 생성, 브랜치 정리와 같은 워크플로우를 안내합니다. 코드가 준비되고 테스트가 완료되었을 때 개발 프로세스를 체계적으로 마무리하기 위해 사용하세요.
