Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

## Unreleased

* Added an `In my browser, I set the viewport to {size}` step, which takes a size like `"390x844"`. The size applies to the open page and to every page loaded later in the same test. Each test still starts at the default 1600x900.

## v0.20.0 (July 7, 2026)

* Added a summary for changed snapshots and failing tests in test outputs
Expand Down
23 changes: 23 additions & 0 deletions docs/content/docs/browser-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,30 @@ steps:
- step: In my browser, I screenshot the element ".modal" to "modal-dialog.png"
```

The viewport is 1600x900 at a device scale factor of 2, so a viewport screenshot
is 3200x1800 pixels and covers only the visible area, not the full page. To capture
at another size, see Setting the Viewport Size below.

Toolproof doesn't include visual snapshot diffs, so these screenshots
should be plugged into another tool if needed for regression testing.

### Setting the Viewport Size

The browser viewport is 1600x900 at a device scale factor of 2 unless you change it:

```yml
steps:
# Set the size before loading, or at any point after
- step: In my browser, I set the viewport to "390x844"
- step: In my browser, I load "/"
- step: In my browser, I screenshot the viewport to "phone.png"
```

The size applies straight away to the open page, so media queries and `resize`
listeners update, and it carries over to every page loaded later in the same test.
Each test starts at the default size. Screenshots keep the scale factor of 2,
so a 390x844 viewport produces a 780x1688 image.

## JavaScript Execution

### Running JavaScript Code
Expand Down Expand Up @@ -300,3 +321,5 @@ failure_screenshot_location: "./test-failures"
```

When browser tests fail, Toolproof can automatically capture screenshots to help with debugging. Set `failure_screenshot_location` to enable this feature.

The viewport size isn't a configuration option. Every test starts at 1600x900, and the `In my browser, I set the viewport to {size}` step changes it within a test.
2 changes: 2 additions & 0 deletions docs/content/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ All configuration options that can be set via command-line or environment variab
| `retry_count` | Number | Number of times to retry failed tests before marking as failed |
| `debugger` | Boolean | Run in debugger mode with step-by-step execution (requires single test) |

The browser viewport size isn't configurable here. Every test starts at 1600x900, and the `In my browser, I set the viewport to {size}` step changes it within a test.

## Command Line Options

Toolproof offers several command-line options to customize its behavior:
Expand Down
3 changes: 2 additions & 1 deletion docs/content/docs/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ For comprehensive browser testing documentation and examples, see [Browser Testi
Instructions:
- `In my browser, I load {url}` - Navigate to a URL
- `In my browser, I evaluate {js}` - Execute JavaScript code
- `In my browser, I screenshot the viewport to {filepath}` - Capture full viewport
- `In my browser, I screenshot the viewport to {filepath}` - Capture the visible viewport, 3200x1800 pixels at the default 1600x900 size
- `In my browser, I screenshot the element {selector} to {filepath}` - Capture specific element
- `In my browser, I set the viewport to {size}` - Resize the viewport, with a size like `"390x844"`. The size carries over to pages loaded later in the same test, and each test starts at 1600x900
- `In my browser, I click {text}` - Click element by visible text
- `In my browser, I hover {text}` - Hover over element by visible text
- `In my browser, I click the selector {selector}` - Click element by CSS selector
Expand Down
1 change: 1 addition & 0 deletions toolproof/src/civilization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub struct Civilization<'u> {
pub last_command_output: Option<CommandOutput>,
pub assigned_server_port: Option<u16>,
pub window: Option<BrowserWindow>,
pub viewport: Option<(i64, i64)>,
pub threads: Vec<JoinHandle<Result<(), std::io::Error>>>,
pub handles: Vec<ServerHandle>,
pub env_vars: HashMap<String, String>,
Expand Down
67 changes: 67 additions & 0 deletions toolproof/src/definitions/browser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::sync::Arc;
use async_trait::async_trait;
use chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotParams;
use chromiumoxide::cdp::browser_protocol::browser::BrowserContextId;
use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
use chromiumoxide::cdp::browser_protocol::target::{
CreateBrowserContextParams, CreateTargetParams,
};
Expand Down Expand Up @@ -209,6 +210,23 @@ impl BrowserWindow {
}
}

async fn set_viewport(&self, width: i64, height: i64) -> Result<(), ToolproofStepError> {
match self {
BrowserWindow::Chrome { page, .. } => page
.execute(SetDeviceMetricsOverrideParams::new(
width, height, 2.0, false,
))
.await
.map(|_| ())
.map_err(|e| ToolproofStepError::Internal(e.into())),
BrowserWindow::Pagebrowse(_) => Err(ToolproofStepError::Internal(
ToolproofInternalError::Custom {
msg: "Setting the viewport not yet implemented for Pagebrowse".to_string(),
},
)),
}
}

async fn evaluate_script(
&self,
script: String,
Expand Down Expand Up @@ -630,6 +648,10 @@ mod load_page {

let window = browser.get_window().await;

if let Some((width, height)) = civ.viewport {
window.set_viewport(width, height).await?;
}

window.navigate(url.to_string(), true).await?;

civ.window = Some(window);
Expand All @@ -639,6 +661,51 @@ mod load_page {
}
}

mod set_viewport {
use super::*;

pub struct SetViewport;

inventory::submit! {
&SetViewport as &dyn ToolproofInstruction
}

fn parse_size(size: &str) -> Option<(i64, i64)> {
let (width, height) = size.trim().split_once('x')?;
let width = width.trim().parse::<i64>().ok()?;
let height = height.trim().parse::<i64>().ok()?;
(width > 0 && height > 0).then_some((width, height))
}

#[async_trait]
impl ToolproofInstruction for SetViewport {
fn segments(&self) -> &'static str {
"In my browser, I set the viewport to {size}"
}

async fn run(
&self,
args: &SegmentArgs<'_>,
civ: &mut Civilization,
) -> Result<(), ToolproofStepError> {
let size = args.get_string("size")?;
let Some((width, height)) = parse_size(&size) else {
return Err(ToolproofStepError::External(ToolproofInputError::StepError {
reason: format!("Viewport size should be a width and height like \"390x844\", found \"{size}\""),
}));
};

civ.viewport = Some((width, height));

if let Some(window) = civ.window.as_ref() {
window.set_viewport(width, height).await?;
}

Ok(())
}
}
}

mod eval_js {

use crate::errors::{ToolproofInternalError, ToolproofTestFailure};
Expand Down
1 change: 1 addition & 0 deletions toolproof/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub async fn run_toolproof_experiment(
last_command_output: None,
assigned_server_port: None,
window: None,
viewport: None,
threads: vec![],
handles: vec![],
env_vars: HashMap::new(),
Expand Down
1 change: 1 addition & 0 deletions toolproof/src/segments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ mod test {
last_command_output: None,
assigned_server_port: None,
window: None,
viewport: None,
threads: vec![],
handles: vec![],
env_vars: HashMap::new(),
Expand Down
55 changes: 55 additions & 0 deletions toolproof/test_suite/browser/viewport.toolproof.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
name: Browser can set the viewport size

steps:
- step: I have a "narrow.toolproof.yml" file with the content {yaml}
yaml: |-
name: Inner narrow viewport test

steps:
- I have a "public/index.html" file with the content "<p>Hello World</p>"
- I serve the directory "public"
- In my browser, I set the viewport to "390x844"
- In my browser, I load "/"
- step: In my browser, I evaluate {js}
js: |-
toolproof.assert_eq(window.innerWidth, 390);
toolproof.assert_eq(window.innerHeight, 844);
toolproof.assert_eq(window.devicePixelRatio, 2);
toolproof.assert(window.matchMedia("(width < 900px)").matches);
- In my browser, I load "/"
- step: In my browser, I evaluate {js}
js: |-
toolproof.assert_eq(window.innerWidth, 390);
- In my browser, I set the viewport to "1200x800"
- step: In my browser, I evaluate {js}
js: |-
toolproof.assert_eq(window.innerWidth, 1200);
toolproof.assert_eq(window.innerHeight, 800);
- step: I have a "default.toolproof.yml" file with the content {yaml}
yaml: |-
name: Inner default viewport test

steps:
- I have a "public/index.html" file with the content "<p>Hello World</p>"
- I serve the directory "public"
- In my browser, I load "/"
- step: In my browser, I evaluate {js}
js: |-
toolproof.assert_eq(window.innerWidth, 1600);
toolproof.assert_eq(window.innerHeight, 900);
- I run "%toolproof_path% --timeout 60"
- step: "stdout should contain 'Total passing tests: 2'"
- step: "stdout should contain 'Failing tests: 0'"
- step: "stdout should contain 'All tests passed'"
- stderr should be empty
- I run "rm narrow.toolproof.yml default.toolproof.yml"
- step: I have a "invalid.toolproof.yml" file with the content {yaml}
yaml: |-
name: Inner invalid viewport test

steps:
- In my browser, I set the viewport to "wide"
- I run "%toolproof_path% --timeout 60 --porcelain" and expect it to fail
- step: "stdout should contain 'Failing tests: 1'"
- step: stdout should contain {expected}
expected: Viewport size should be a width and height like "390x844", found "wide"
Loading