/
live_view_test.ex
1688 lines (1285 loc) · 52.1 KB
/
live_view_test.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Phoenix.LiveViewTest do
@moduledoc """
Conveniences for testing Phoenix LiveViews.
In LiveView tests, we interact with views via process
communication in substitution of a browser. Like a browser,
our test process receives messages about the rendered updates
from the view which can be asserted against to test the
life-cycle and behavior of LiveViews and their children.
## LiveView Testing
The life-cycle of a LiveView as outlined in the `Phoenix.LiveView`
docs details how a view starts as a stateless HTML render in a disconnected
socket state. Once the browser receives the HTML, it connects to the
server and a new LiveView process is started, remounted in a connected
socket state, and the view continues statefully. The LiveView test functions
support testing both disconnected and connected mounts separately, for example:
import Plug.Conn
import Phoenix.ConnTest
import Phoenix.LiveViewTest
@endpoint MyEndpoint
test "disconnected and connected mount", %{conn: conn} do
conn = get(conn, "/my-path")
assert html_response(conn, 200) =~ "<h1>My Disconnected View</h1>"
{:ok, view, html} = live(conn)
end
test "redirected mount", %{conn: conn} do
assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "my-path")
end
Here, we start by using the familiar `Phoenix.ConnTest` function, `get/2` to
test the regular HTTP GET request which invokes mount with a disconnected socket.
Next, `live/1` is called with our sent connection to mount the view in a connected
state, which starts our stateful LiveView process.
In general, it's often more convenient to test the mounting of a view
in a single step, provided you don't need the result of the stateless HTTP
render. This is done with a single call to `live/2`, which performs the
`get` step for us:
test "connected mount", %{conn: conn} do
{:ok, _view, html} = live(conn, "/my-path")
assert html =~ "<h1>My Connected View</h1>"
end
## Testing Events
The browser can send a variety of events to a LiveView via `phx-` bindings,
which are sent to the `handle_event/3` callback. To test events sent by the
browser and assert on the rendered side effect of the event, use the
`render_*` functions:
* `render_click/1` - sends a phx-click event and value, returning
the rendered result of the `handle_event/3` callback.
* `render_focus/2` - sends a phx-focus event and value, returning
the rendered result of the `handle_event/3` callback.
* `render_blur/1` - sends a phx-blur event and value, returning
the rendered result of the `handle_event/3` callback.
* `render_submit/1` - sends a form phx-submit event and value, returning
the rendered result of the `handle_event/3` callback.
* `render_change/1` - sends a form phx-change event and value, returning
the rendered result of the `handle_event/3` callback.
* `render_keydown/1` - sends a form phx-keydown event and value, returning
the rendered result of the `handle_event/3` callback.
* `render_keyup/1` - sends a form phx-keyup event and value, returning
the rendered result of the `handle_event/3` callback.
* `render_hook/3` - sends a hook event and value, returning
the rendered result of the `handle_event/3` callback.
For example:
{:ok, view, _html} = live(conn, "/thermo")
assert view
|> element("button#inc")
|> render_click() =~ "The temperature is: 31℉"
In the example above, we are looking for a particular element on the page
and triggering its phx-click event. LiveView takes care of making sure the
element has a phx-click and automatically sends its values to the server.
You can also bypass the element lookup and directly trigger the LiveView
event in most functions:
assert render_click(view, :inc, %{}) =~ "The temperature is: 31℉"
The `element` style is preferred as much as possible, as it helps LiveView
perform validations and ensure the events in the HTML actually matches the
event names on the server.
## Testing regular messages
LiveViews are `GenServer`'s under the hood, and can send and receive messages
just like any other server. To test the side effects of sending or receiving
messages, simply message the view and use the `render` function to test the
result:
send(view.pid, {:set_temp, 50})
assert render(view) =~ "The temperature is: 50℉"
## Testing components
There are two main mechanisms for testing components. To test stateless
components or just a regular rendering of a component, one can use
`render_component/2`:
assert render_component(MyComponent, id: 123, user: %User{}) =~
"some markup in component"
If you want to test how components are mounted by a LiveView and
interact with DOM events, you can use the regular `live/2` macro
to build the LiveView with the component and then scope events by
passing the view and a **DOM selector** in a list:
{:ok, view, html} = live(conn, "/users")
html = view |> element("#user-13 a", "Delete") |> render_click()
refute html =~ "user-13"
refute view |> element("#user-13") |> has_element?()
In the example above, LiveView will lookup for an element with
ID=user-13 and retrieve its `phx-target`. If `phx-target` points
to a component, that will be the component used, otherwise it will
fallback to the view.
"""
@flash_cookie "__phoenix_flash__"
require Phoenix.ConnTest
require Phoenix.ChannelTest
alias Phoenix.LiveView.{Diff, Socket}
alias Phoenix.LiveViewTest.{ClientProxy, DOM, Element, View, Upload, UploadClient}
@doc """
Puts connect params to be used on LiveView connections.
See `Phoenix.LiveView.get_connect_params/1`.
"""
def put_connect_params(conn, params) when is_map(params) do
Plug.Conn.put_private(conn, :live_view_connect_params, params)
end
@doc """
Puts connect info to be used on LiveView connections.
See `Phoenix.LiveView.get_connect_info/1`.
"""
def put_connect_info(conn, params) when is_map(params) do
Plug.Conn.put_private(conn, :live_view_connect_info, params)
end
@doc """
Spawns a connected LiveView process.
If a `path` is given, then a regular `get(conn, path)`
is done and the page is upgraded to a `LiveView`. If
no path is given, it assumes a previously rendered
`%Plug.Conn{}` is given, which will be converted to
a `LiveView` immediately.
## Examples
{:ok, view, html} = live(conn, "/path")
assert view.module = MyLive
assert html =~ "the count is 3"
assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "/path")
"""
defmacro live(conn, path \\ nil) do
quote bind_quoted: binding(), generated: true do
cond do
is_binary(path) ->
Phoenix.LiveViewTest.__live__(get(conn, path), path)
is_nil(path) ->
Phoenix.LiveViewTest.__live__(conn)
true ->
raise RuntimeError, "path must be nil or a binary, got: #{inspect(path)}"
end
end
end
@doc """
Spawns a connected LiveView process mounted in isolation as the sole rendered element.
Useful for testing LiveViews that are not directly routable, such as those
built as small components to be re-used in multiple parents. Testing routable
LiveViews is still recommended whenever possible since features such as
live navigation require routable LiveViews.
## Options
* `:session` - the session to be given to the LiveView
All other options are forwarded to the LiveView for rendering. Refer to
`Phoenix.LiveView.Helpers.live_render/3` for a list of supported render
options.
## Examples
{:ok, view, html} =
live_isolated(conn, MyAppWeb.ClockLive, session: %{"tz" => "EST"})
Use `put_connect_params/2` to put connect params for a call to
`Phoenix.LiveView.get_connect_params/1` in `c:Phoenix.LiveView.mount/3`:
{:ok, view, html} =
conn
|> put_connect_params(%{"param" => "value"})
|> live_isolated(AppWeb.ClockLive, session: %{"tz" => "EST"})
"""
defmacro live_isolated(conn, live_view, opts \\ []) do
endpoint = Module.get_attribute(__CALLER__.module, :endpoint)
quote bind_quoted: binding(), unquote: true do
unquote(__MODULE__).__isolated__(conn, endpoint, live_view, opts)
end
end
@doc false
def __isolated__(conn, endpoint, live_view, opts) do
put_in(conn.private[:phoenix_endpoint], endpoint || raise("no @endpoint set in test module"))
|> Plug.Test.init_test_session(%{})
|> Phoenix.LiveView.Router.fetch_live_flash([])
|> Phoenix.LiveView.Controller.live_render(live_view, opts)
|> connect_from_static_token(nil)
end
@doc false
def __live__(%Plug.Conn{state: state, status: status} = conn) do
path = rebuild_path(conn)
case {state, status} do
{:sent, 200} ->
connect_from_static_token(conn, path)
{:sent, 302} ->
error_redirect_conn(conn)
{:sent, _} ->
raise ArgumentError,
"request to #{conn.request_path} received unexpected #{status} response"
{_, _} ->
raise ArgumentError, """
a request has not yet been sent.
live/1 must use a connection with a sent response. Either call get/2
prior to live/1, or use live/2 while providing a path to have a get
request issued for you. For example issuing a get yourself:
{:ok, view, _html} =
conn
|> get("#{path}")
|> live()
or performing the GET and live connect in a single step:
{:ok, view, _html} = live(conn, "#{path}")
"""
end
end
@doc false
def __live__(conn, path) do
connect_from_static_token(conn, path)
end
defp connect_from_static_token(
%Plug.Conn{status: 200, assigns: %{live_module: live_module}} = conn,
path
) do
DOM.ensure_loaded!()
router =
try do
Phoenix.Controller.router_module(conn)
rescue
KeyError -> nil
end
start_proxy(path, %{
html: Phoenix.ConnTest.html_response(conn, 200),
connect_params: conn.private[:live_view_connect_params] || %{},
connect_info: conn.private[:live_view_connect_info] || %{},
live_module: live_module,
router: router,
endpoint: Phoenix.Controller.endpoint_module(conn),
session: maybe_get_session(conn),
url: Plug.Conn.request_url(conn)
})
end
defp connect_from_static_token(%Plug.Conn{status: 200}, _path) do
{:error, :nosession}
end
defp connect_from_static_token(%Plug.Conn{status: redir} = conn, _path)
when redir in [301, 302] do
error_redirect_conn(conn)
end
defp error_redirect_conn(conn) do
to = hd(Plug.Conn.get_resp_header(conn, "location"))
opts =
if flash = conn.private[:phoenix_flash] do
endpoint = Phoenix.Controller.endpoint_module(conn)
%{to: to, flash: Phoenix.LiveView.Utils.sign_flash(endpoint, flash)}
else
%{to: to}
end
{:error, {error_redirect_key(conn), opts}}
end
defp error_redirect_key(%{private: %{phoenix_live_redirect: true}}), do: :live_redirect
defp error_redirect_key(_), do: :redirect
defp start_proxy(path, %{} = opts) do
ref = make_ref()
opts =
Map.merge(opts, %{
caller: {self(), ref},
html: opts.html,
connect_params: opts.connect_params,
connect_info: opts.connect_info,
live_module: opts.live_module,
endpoint: opts.endpoint,
session: opts.session,
url: opts.url,
test_supervisor: fetch_test_supervisor!()
})
case ClientProxy.start_link(opts) do
{:ok, _} ->
receive do
{^ref, {:ok, view, html}} -> {:ok, view, html}
end
{:error, reason} ->
exit({reason, {__MODULE__, :live, [path]}})
:ignore ->
receive do
{^ref, {:error, reason}} -> {:error, reason}
end
end
end
# TODO: replace with ExUnit.Case.fetch_test_supervisor!() when we require Elixir v1.11.
defp fetch_test_supervisor!() do
case ExUnit.OnExitHandler.get_supervisor(self()) do
{:ok, nil} ->
opts = [strategy: :one_for_one, max_restarts: 1_000_000, max_seconds: 1]
{:ok, sup} = Supervisor.start_link([], opts)
ExUnit.OnExitHandler.put_supervisor(self(), sup)
sup
{:ok, sup} ->
sup
:error ->
raise ArgumentError, "fetch_test_supervisor!/0 can only be invoked from the test process"
end
end
defp maybe_get_session(%Plug.Conn{} = conn) do
try do
Plug.Conn.get_session(conn)
rescue
_ -> %{}
end
end
defp rebuild_path(%Plug.Conn{request_path: request_path, query_string: ""}),
do: request_path
defp rebuild_path(%Plug.Conn{request_path: request_path, query_string: query_string}),
do: request_path <> "?" <> query_string
@doc """
Renders a component.
The first argument may either be a function component, as an
anonymous function:
assert render_component(&Weather.city/1, name: "Kraków") =~
"some markup in component"
Or a stateful component as a module. In this case, this function
will mount, update, and render the component. The `:id` option is
a required argument:
assert render_component(MyComponent, id: 123, user: %User{}) =~
"some markup in component"
If your component is using the router, you can pass it as argument:
assert render_component(MyComponent, %{id: 123, user: %User{}}, router: SomeRouter) =~
"some markup in component"
"""
defmacro render_component(component, assigns, opts \\ []) do
endpoint = Module.get_attribute(__CALLER__.module, :endpoint)
quote do
component = unquote(component)
Phoenix.LiveViewTest.__render_component__(
unquote(endpoint),
if(is_atom(component), do: component.__live__(), else: component),
unquote(assigns),
unquote(opts)
)
end
end
@doc false
def __render_component__(endpoint, %{module: component}, assigns, opts) do
socket = %Socket{endpoint: endpoint, router: opts[:router]}
assigns = Map.new(assigns)
# TODO: Make the ID required once we support only stateful module components as live_component
mount_assigns = if assigns[:id], do: %{myself: %Phoenix.LiveComponent.CID{cid: -1}}, else: %{}
socket
|> Diff.component_to_rendered(component, assigns, mount_assigns)
|> rendered_to_iodata(socket)
end
def __render_component__(endpoint, function, assigns, opts) when is_function(function, 1) do
socket = %Socket{endpoint: endpoint, router: opts[:router]}
assigns
|> Map.new()
|> function.()
|> rendered_to_iodata(socket)
end
defp rendered_to_iodata(rendered, socket) do
{_, diff, _} = Diff.render(socket, rendered, Diff.new_components())
diff |> Diff.to_iodata() |> IO.iodata_to_binary()
end
@doc """
Sends a click event given by `element` and returns the rendered result.
The `element` is created with `element/3` and must point to a single
element on the page with a `phx-click` attribute in it. The event name
given set on `phx-click` is then sent to the appropriate LiveView
(or component if `phx-target` is set accordingly). All `phx-value-*`
entries in the element are sent as values. Extra values can be given
with the `value` argument.
If the element is does not have a `phx-click` attribute but it is
a link (the `<a>` tag), the link will be followed accordingly:
* if the link is a `live_patch`, the current view will be patched
* if the link is a `live_redirect`, this function will return
`{:error, {:live_redirect, %{to: url}}}`, which can be followed
with `follow_redirect/2`
* if the link is a regular link, this function will return
`{:error, {:redirect, %{to: url}}}`, which can be followed
with `follow_redirect/2`
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("buttons", "Increment")
|> render_click() =~ "The temperature is: 30℉"
"""
def render_click(element, value \\ %{})
def render_click(%Element{} = element, value), do: render_event(element, :click, value)
def render_click(view, event), do: render_click(view, event, %{})
@doc """
Sends a click `event` to the `view` with `value` and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temperature is: 30℉"
assert render_click(view, :inc) =~ "The temperature is: 31℉"
"""
def render_click(view, event, value) do
render_event(view, :click, event, value)
end
@doc """
Sends a form submit event given by `element` and returns the rendered result.
The `element` is created with `element/3` and must point to a single
element on the page with a `phx-submit` attribute in it. The event name
given set on `phx-submit` is then sent to the appropriate LiveView
(or component if `phx-target` is set accordingly). All `phx-value-*`
entries in the element are sent as values. Extra values, including hidden
input fields, can be given with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("form")
|> render_submit(%{deg: 123, avatar: upload}) =~ "123 exceeds limits"
To submit a form along with some with hidden input values:
assert view
|> form("#term", user: %{name: "hello"})
|> render_submit(%{user: %{"hidden_field" => "example"}}) =~ "Name updated"
"""
def render_submit(element, value \\ %{})
def render_submit(%Element{} = element, value), do: render_event(element, :submit, value)
def render_submit(view, event), do: render_submit(view, event, %{})
@doc """
Sends a form submit event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_submit(view, :refresh, %{deg: 32}) =~ "The temp is: 32℉"
"""
def render_submit(view, event, value) do
render_event(view, :submit, event, value)
end
@doc """
Sends a form change event given by `element` and returns the rendered result.
The `element` is created with `element/3` and must point to a single
element on the page with a `phx-change` attribute in it. The event name
given set on `phx-change` is then sent to the appropriate LiveView
(or component if `phx-target` is set accordingly). All `phx-value-*`
entries in the element are sent as values.
If you need to pass any extra values or metadata, such as the "_target"
parameter, you can do so by giving a map under the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("form")
|> render_change(%{deg: 123}) =~ "123 exceeds limits"
# Passing metadata
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("form")
|> render_change(%{_target: ["deg"], deg: 123}) =~ "123 exceeds limits"
As with `render_submit/2`, hidden input field values can be provided like so:
refute view
|> form("#term", user: %{name: "hello"})
|> render_change(%{user: %{"hidden_field" => "example"}}) =~ "can't be blank"
"""
def render_change(element, value \\ %{})
def render_change(%Element{} = element, value), do: render_event(element, :change, value)
def render_change(view, event), do: render_change(view, event, %{})
@doc """
Sends a form change event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_change(view, :validate, %{deg: 123}) =~ "123 exceeds limits"
"""
def render_change(view, event, value) do
render_event(view, :change, event, value)
end
@doc """
Sends a keydown event given by `element` and returns the rendered result.
The `element` is created with `element/3` and must point to a single element
on the page with a `phx-keydown` or `phx-window-keydown` attribute in it.
The event name given set on `phx-keydown` is then sent to the appropriate
LiveView (or component if `phx-target` is set accordingly). All `phx-value-*`
entries in the element are sent as values. Extra values can be given with
the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert view |> element("#inc") |> render_keydown() =~ "The temp is: 31℉"
"""
def render_keydown(element, value \\ %{})
def render_keydown(%Element{} = element, value),
do: render_event(element, :keydown, value)
def render_keydown(view, event), do: render_keydown(view, event, %{})
@doc """
Sends a keydown event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_keydown(view, :inc) =~ "The temp is: 31℉"
"""
def render_keydown(view, event, value) do
render_event(view, :keydown, event, value)
end
@doc """
Sends a keyup event given by `element` and returns the rendered result.
The `element` is created with `element/3` and must point to a single
element on the page with a `phx-keyup` or `phx-window-keyup` attribute
in it. The event name given set on `phx-keyup` is then sent to the
appropriate LiveView (or component if `phx-target` is set accordingly).
All `phx-value-*` entries in the element are sent as values. Extra values
can be given with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert view |> element("#inc") |> render_keyup() =~ "The temp is: 31℉"
"""
def render_keyup(element, value \\ %{})
def render_keyup(%Element{} = element, value), do: render_event(element, :keyup, value)
def render_keyup(view, event), do: render_keyup(view, event, %{})
@doc """
Sends a keyup event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_keyup(view, :inc) =~ "The temp is: 31℉"
"""
def render_keyup(view, event, value) do
render_event(view, :keyup, event, value)
end
@doc """
Sends a blur event given by `element` and returns the rendered result.
The `element` is created with `element/3` and must point to a single
element on the page with a `phx-blur` attribute in it. The event name
given set on `phx-blur` is then sent to the appropriate LiveView
(or component if `phx-target` is set accordingly). All `phx-value-*`
entries in the element are sent as values. Extra values can be given
with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("#inactive")
|> render_blur() =~ "Tap to wake"
"""
def render_blur(element, value \\ %{})
def render_blur(%Element{} = element, value), do: render_event(element, :blur, value)
def render_blur(view, event), do: render_blur(view, event, %{})
@doc """
Sends a blur event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_blur(view, :inactive) =~ "Tap to wake"
"""
def render_blur(view, event, value) do
render_event(view, :blur, event, value)
end
@doc """
Sends a focus event given by `element` and returns the rendered result.
The `element` is created with `element/3` and must point to a single
element on the page with a `phx-focus` attribute in it. The event name
given set on `phx-focus` is then sent to the appropriate LiveView
(or component if `phx-target` is set accordingly). All `phx-value-*`
entries in the element are sent as values. Extra values can be given
with the `value` argument.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert view
|> element("#inactive")
|> render_focus() =~ "Tap to wake"
"""
def render_focus(element, value \\ %{})
def render_focus(%Element{} = element, value), do: render_event(element, :focus, value)
def render_focus(view, event), do: render_focus(view, event, %{})
@doc """
Sends a focus event to the view and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_focus(view, :inactive) =~ "Tap to wake"
"""
def render_focus(view, event, value) do
render_event(view, :focus, event, value)
end
@doc """
Sends a hook event to the view or an element and returns the rendered result.
It returns the contents of the whole LiveView or an `{:error, redirect}`
tuple.
## Examples
{:ok, view, html} = live(conn, "/thermo")
assert html =~ "The temp is: 30℉"
assert render_hook(view, :refresh, %{deg: 32}) =~ "The temp is: 32℉"
If you are pushing events from a hook to a component, then you must pass
an `element`, created with `element/3`, as first argument and it must point
to a single element on the page with a `phx-target` attribute in it:
{:ok, view, _html} = live(conn, "/thermo")
assert view
|> element("#thermo-component")
|> render_hook(:refresh, %{deg: 32}) =~ "The temp is: 32℉"
"""
def render_hook(view_or_element, event, value \\ %{})
def render_hook(%Element{} = element, event, value) do
render_event(%{element | event: to_string(event)}, :hook, value)
end
def render_hook(view, event, value) do
render_event(view, :hook, event, value)
end
defp render_event(%Element{} = element, type, value) when is_map(value) or is_list(value) do
call(element, {:render_event, element, type, value})
end
defp render_event(%View{} = view, type, event, value) when is_map(value) or is_list(value) do
call(view, {:render_event, {proxy_topic(view), to_string(event), view.target}, type, value})
end
@doc """
Simulates a `live_patch` to the given `path` and returns the rendered result.
"""
def render_patch(%View{} = view, path) when is_binary(path) do
call(view, {:render_patch, proxy_topic(view), path})
end
@doc """
Returns the current list of LiveView children for the `parent` LiveView.
Children are returned in the order they appear in the rendered HTML.
## Examples
{:ok, view, _html} = live(conn, "/thermo")
assert [clock_view] = live_children(view)
assert render_click(clock_view, :snooze) =~ "snoozing"
"""
def live_children(%View{} = parent) do
call(parent, {:live_children, proxy_topic(parent)})
end
@doc """
Gets the nested LiveView child by `child_id` from the `parent` LiveView.
## Examples
{:ok, view, _html} = live(conn, "/thermo")
assert clock_view = find_live_child(view, "clock")
assert render_click(clock_view, :snooze) =~ "snoozing"
"""
def find_live_child(%View{} = parent, child_id) do
parent
|> live_children()
|> Enum.find(fn %View{id: id} -> id == child_id end)
end
@doc """
Checks if the given element exists on the page.
## Examples
assert view |> element("#some-element") |> has_element?()
"""
def has_element?(%Element{} = element) do
call(element, {:render_element, :has_element?, element})
end
@doc """
Checks if the given `selector` with `text_filter` is on `view`.
See `element/3` for more information.
## Examples
assert has_element?(view, "#some-element")
"""
def has_element?(%View{} = view, selector, text_filter \\ nil) do
has_element?(element(view, selector, text_filter))
end
@doc """
Returns the HTML string of the rendered view or element.
If a view is provided, the entire LiveView is rendered.
If a view after calling `with_target/2` or an element
are given, only that particular context is returned.
## Examples
{:ok, view, _html} = live(conn, "/thermo")
assert render(view) =~ ~s|<button id="alarm">Snooze</div>|
assert view
|> element("#alarm")
|> render() == "Snooze"
"""
def render(view_or_element) do
view_or_element
|> render_tree()
|> DOM.to_html()
end
@doc """
Sets the target of the view for events.
This emulates `phx-target` directly in tests, without
having to dispatch the event to a specific element.
This can be useful for invoking events to one or
multiple components at the same time:
view
|> with_target("#user-1,#user-2")
|> render_click("Hide", %{})
"""
def with_target(%View{} = view, target) do
%{view | target: target}
end
defp render_tree(%View{} = view) do
render_tree(view, {proxy_topic(view), "render", view.target})
end
defp render_tree(%Element{} = element) do
render_tree(element, element)
end
defp render_tree(view_or_element, topic_or_element) do
call(view_or_element, {:render_element, :find_element, topic_or_element})
end
defp call(view_or_element, tuple) do
try do
GenServer.call(proxy_pid(view_or_element), tuple, 30_000)
catch
:exit, {{:shutdown, {kind, opts}}, _} when kind in [:redirect, :live_redirect] ->
{:error, {kind, opts}}
:exit, {{exception, stack}, _} ->
exit({{exception, stack}, {__MODULE__, :call, [view_or_element]}})
else
:ok -> :ok
{:ok, result} -> result
{:raise, exception} -> raise exception
end
end
@doc """
Returns an element to scope a function to.
It expects the current LiveView, a query selector, and a text filter.
An optional text filter may be given to filter the results by the query
selector. If the text filter is a string or a regex, it will match any
element that contains the string or matches the regex. After the text
filter is applied, only one element must remain, otherwise an error is
raised.
If no text filter is given, then the query selector itself must return
a single element.
assert view
|> element("#term a:first-child()", "Increment")
|> render() =~ "Increment</a>"
Attribute selectors are also supported, and may be used on special cases
like ids which contain periods:
assert view
|> element(~s{[href="/foo"][id="foo.bar.baz"]})
|> render() =~ "Increment</a>"
"""
def element(%View{proxy: proxy}, selector, text_filter \\ nil) when is_binary(selector) do
%Element{proxy: proxy, selector: selector, text_filter: text_filter}
end
@doc """
Returns a form element to scope a function to.
It expects the current LiveView, a query selector, and the form data.
The query selector must return a single element.
The form data will be validated directly against the form markup and
make sure the data you are changing/submitting actually exists, failing
otherwise.
## Examples