如何让jest命令静默输出并通过退出码返回清晰的成败提示
Hey there! If you want to run Jest without any logs cluttering your output, but still get a clear message about whether tests passed or failed based on the command's exit code, here's how you can do it:
Unix/Linux/macOS (Bash/Zsh)
Use this one-liner to silence all Jest output and show a simple success/fail message:
jest > /dev/null 2>&1 && echo "✅ Jest tests passed successfully!" || echo "❌ Jest tests failed!"
Let’s break this down:
> /dev/null: Redirects all standard output (like test results, progress logs) to the null device (discards it entirely).2>&1: Redirects standard error (like error messages, stack traces) to the same place as standard output, so those get discarded too.&& echo ...: If Jest exits with a code of0(success), this runs the green success message.|| echo ...: If Jest exits with any non-zero code (failure), this runs the red failure message.
Windows (PowerShell)
For PowerShell users, the syntax is a bit different but achieves the same goal:
jest *> $null; if ($LASTEXITCODE -eq 0) { Write-Host "✅ Jest tests passed successfully!" -ForegroundColor Green } else { Write-Host "❌ Jest tests failed!" -ForegroundColor Red }
*> $null: Discards all output (both standard and error streams) in one go.$LASTEXITCODE: PowerShell’s variable that stores the exit code of the last executed external command (Jest, in this case).- The
if/elseblock checks the exit code and prints colored messages for better visual clarity.
Add to package.json Scripts
To make this easier to run regularly, add a dedicated script to your package.json:
{ "scripts": { "test:silent": "jest > /dev/null 2>&1 && echo \"✅ Jest tests passed successfully!\" || echo \"❌ Jest tests failed!\"" } }
Now you can just run npm run test:silent (or yarn test:silent) whenever you want a quiet test run with straightforward feedback.
Why this works
Jest doesn’t have a built-in flag to completely silence output while only showing a pass/fail message, but we can leverage shell redirection and exit codes to pull this off. All programs return an exit code: 0 means success, and any non-zero code indicates an error. We use this universal convention to trigger the appropriate message after silencing all Jest output.
内容的提问来源于stack exchange,提问作者ThomasReggi

