> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Elixir Phoenix and Phoenix LiveView

In order to create snapshots in Phoenix, you'll need to use the library [`ex_snappy`](https://hex.pm/packages/ex_snappy)

## Installation

```elixir
def deps do
  [
    {:ex_snappy, "~> 0.6.3", only: :test}
  ]
end
```

## Configuration

`live(...)` returns a full page, including the `<head>` that loads your CSS. `render(view)` and `render_component(...)` only return a fragment, with nothing to load your styles. ExSnappy wraps fragments in your app's root layout, so point it at the layout you already have:

```elixir
# config/test.exs
config :ex_snappy,
  layout: {MyAppWeb.Layouts, :root}
```

In Phoenix 1.7 and 1.8 the app layout is already rendered inside the LiveView, so the root layout is all that's missing.

`<script>` tags are removed before the page is sent, so JavaScript (the socket, the topbar, a theme toggle) never runs and can't make screenshots flaky.

If your root layout reads assigns other than `page_title` and `flash`, supply them:

```elixir
config :ex_snappy,
  layout: {MyAppWeb.Layouts, :root},
  layout_assigns: %{current_scope: nil}
```

Both can be overridden for a single snapshot: `snap(html, layout: false)` or `snap(html, layout_assigns: %{current_scope: scope})`.

:::info
Projects set up before ExSnappy 0.6 may have a `wrapper_fn` in their config, a function that returns the HTML around each fragment. It still works, but you can delete it and use `layout` instead. If both are set, `layout` wins.
:::

If you're running tests locally, you likely don't want to be running the visual regression tests, so we only execute if you explicitly enable things.  Suggested way of dealing with this below

```elixir
config :ex_snappy,
  enabled: System.get_env("EX_SNAPPY_ENABLED") == "true"
```

If you don't wish your screenshots to be full_page you can turn this off globally

```elixir
config :ex_snappy,
  full_page: false
```

# Setup

To execute the visual regression tests, you'll need to add some configuration data by creating a `.get-snappy.yml` file

For example:

```yml
local_dist_dir: "priv/static"
snappy_workers: 4
test_command: "mix do assets.build + test"
browsers: ["chrome", "webkit", "firefox"]
```

The `local_dist_dir` is use to allow the rendering service to know where your static assets are.  For most Phoenix projects, this would be `priv/static`

`snappy_workers` are the number of workers per browser.  This allows faster rendering of snapshots, but can be reduced if you are resource limited.  In the example below there would be a total of 12 browser instances (4 x 3 browser).

`browsers` Are the browsers you wish to render in

`test_command` is the shell command you wish to run to execute your test suite.

You'll also need to set some environment variables, an example of this is below, but you'd likely get the COMMIT and BRANCH from your CI provider.

```shell
COMMIT=$(git rev-parse HEAD)
BRANCH=$(git rev-parse --abbrev-ref HEAD)

export GET_SNAPPY_API_KEY="your-project-api-ket"
export GET_SNAPPY_COMMIT=$COMMIT
export GET_SNAPPY_BRANCH=$BRANCH
```

Finally, execute the tests you'd run something like this (further information on `EX_SNAPPY_ENABLED` below):

`EX_SNAPPY_ENABLED=true get-snappy snapshot-run`

## Usage

The `snap` macro can be used in three forms.  See [`ExSnappy`](https://hexdocs.pm/ex_snappy/ExSnappy.html) module for further details.

Key steps:

1. `import ExSnappy` to make the `snap` macro available

2. Use the `snap` function to capture screenshots.

:::warning
Screenshot names are automatically generated based on the name of the `test` function, but if you take multiple screenshots in a single test, you'll need to provide an explicit name to be appended to the test name.
:::

```elixir
defmodule MyApp.LiveIndexTest do
  use MyApp.ConnCase, async: true
  import Phoenix.LiveViewTest

  import ExSnappy
end
```

Then pass `snap` the `html` from a `live()` call, the view itself (`snap(view)` renders it for you), the result of `render(view)`, or the output of `render_component`.

### Rendering from `live()`

```elixir
defmodule MyApp.LiveIndexTest do
  use MyApp.ConnCase, async: true
  import Phoenix.LiveViewTest

  import ExSnappy
  
  describe "my tests" do
    test "List projects and project builds", %{conn: conn, project: project} do
      # Visit top level builds page
      {:ok, index_live, html} = live(conn, ~p"/app/builds")

      assert html =~ "Builds"
      assert html =~ project.name

      snap(html)
    end
  end
end
```

### Using `render()`

```elixir
defmodule MyApp.LiveIndexTest do
  use MyApp.ConnCase, async: true
  import Phoenix.LiveViewTest

  import ExSnappy
  
  describe "my tests" do
    test "List projects and project builds", %{conn: conn, project: project} do
      # Visit top level builds page
      {:ok, index_live, html} = live(conn, ~p"/app/builds")

      assert html =~ "Builds"
      assert html =~ project.name

      snap(render(index_live))
    end
  end
end
```

### Using `render_component()`

```elixir
defmodule MyApp.PaginationGeneratorTest do
  use ExUnit.Case, async: true
  import Phoenix.LiveViewTest
  import ExSnappy

  test "Lists elements when no next or previous" do
    meta = %Flop.Meta{
      current_page: 1,
      total_pages: 10
    }

    rendered = render_component(&MyApp.Pagination.paginate/1, meta: meta, base_url: "/hello")

    snap(rendered)

    assert Floki.find(rendered, "a") |> length() == 10
  end
end
```

# Taking multiple screenshots in a single test

Simply provide an explicit name for all but the first call to `snap`.

```elixir
   test "multiple screenshots" do
      {:ok, index_live, html} = live(conn, ~p"/app/projects")

      snap(html)

      assert index_live |> element("a", "New Project") |> render_click() =~
               "New Project"

      render_async(index_live)

      snap(render(index_live), name: "after render" )

      assert index_live
             |> form("#project-form", project: @invalid_attrs)
             |> render_change() =~ "can&#39;t be blank"

      snap( render(index_live), name: "With errors")

      assert index_live
             |> form("#project-form",
               project:
                 @create_attrs
                 |> Map.put(:repository_full_name, "some/repo")
             )
             |> render_submit()

      snap(render(index_live), name: "With errors fixed")
   end
```

## Additional Options

You can pass `:playwright_options` to set options for Playwright.

### Playwright Options

`:full_page`, which defaults to true. You can globally set whether to enable full page screenshots by setting the `:full_page` option in your config file to false. Any `playwright_options` you pass are merged over this default, so leaving `full_page` out keeps it.

`:dark_mode`, which defaults to false.

`:locator`, which can be a CSS selector which should target a single element. This will limit the screenshot size to the bounding box of the element. This is useful for testing specific elements and components.

### General options

`:dimensions`, which can be a list of maps with :width and :height keys.
Where dimensions aren't specified, the default will be 1920x1080
Example

```elixir
snap(html, name: "my_snapshot", 
  playwright_options: %{
    dark_mode: true,
    locator: ".my-element"
  },
  dimensions: [
    %{width: 1280, height: 720},
    %{width: 1920, height: 1080}
  ]
)
```
