1Test::Mojo(3)         User Contributed Perl Documentation        Test::Mojo(3)
2
3
4

NAME

6       Test::Mojo - Testing Mojo
7

SYNOPSIS

9         use Test::More;
10         use Test::Mojo;
11
12         my $t = Test::Mojo->new('MyApp');
13
14         # HTML/XML
15         $t->get_ok('/welcome')->status_is(200)->text_is('div#message' => 'Hello!');
16
17         # JSON
18         $t->post_ok('/search.json' => form => {q => 'Perl'})
19           ->status_is(200)
20           ->header_is('Server' => 'Mojolicious (Perl)')
21           ->header_isnt('X-Bender' => 'Bite my shiny metal ass!')
22           ->json_is('/results/4/title' => 'Perl rocks!')
23           ->json_like('/results/7/title' => qr/Perl/);
24
25         # WebSocket
26         $t->websocket_ok('/echo')
27           ->send_ok('hello')
28           ->message_ok
29           ->message_is('echo: hello')
30           ->finish_ok;
31
32         done_testing();
33

DESCRIPTION

35       Test::Mojo is a test user agent based on Mojo::UserAgent, it is usually
36       used together with Test::More to test Mojolicious applications. Just
37       run your tests with prove.
38
39         $ prove -l -v
40         $ prove -l -v t/foo.t
41
42       If it is not already defined, the "MOJO_LOG_LEVEL" environment variable
43       will be set to "debug" or "fatal", depending on the value of the
44       "HARNESS_IS_VERBOSE" environment variable. And to make it esier to test
45       HTTPS/WSS web services "insecure" in Mojo::UserAgent will be activated
46       by default for "ua".
47
48       See Mojolicious::Guides::Testing for more.
49

ATTRIBUTES

51       Test::Mojo implements the following attributes.
52
53   message
54         my $msg = $t->message;
55         $t      = $t->message([text => $bytes]);
56
57       Current WebSocket message represented as an array reference containing
58       the frame type and payload.
59
60         # More specific tests
61         use Mojo::JSON 'decode_json';
62         my $hash = decode_json $t->message->[1];
63         is ref $hash, 'HASH', 'right reference';
64         is $hash->{foo}, 'bar', 'right value';
65
66         # Test custom message
67         $t->message([binary => $bytes])
68           ->json_message_has('/foo/bar')
69           ->json_message_hasnt('/bar')
70           ->json_message_is('/foo/baz' => {yada => [1, 2, 3]});
71
72   success
73         my $bool = $t->success;
74         $t       = $t->success($bool);
75
76       True if the last test was successful.
77
78         # Build custom tests
79         my $location_is = sub {
80           my ($t, $value, $desc) = @_;
81           $desc ||= "Location: $value";
82           local $Test::Builder::Level = $Test::Builder::Level + 1;
83           return $t->success(is($t->tx->res->headers->location, $value, $desc));
84         };
85         $t->get_ok('/')
86           ->status_is(302)
87           ->$location_is('https://mojolicious.org')
88           ->or(sub { diag 'Must have been Joel!' });
89
90   tx
91         my $tx = $t->tx;
92         $t     = $t->tx(Mojo::Transaction::HTTP->new);
93
94       Current transaction, usually a Mojo::Transaction::HTTP or
95       Mojo::Transaction::WebSocket object.
96
97         # More specific tests
98         is $t->tx->res->json->{foo}, 'bar', 'right value';
99         ok $t->tx->res->content->is_multipart, 'multipart content';
100         is $t->tx->previous->res->code, 302, 'right status';
101
102   ua
103         my $ua = $t->ua;
104         $t     = $t->ua(Mojo::UserAgent->new);
105
106       User agent used for testing, defaults to a Mojo::UserAgent object.
107
108         # Allow redirects
109         $t->ua->max_redirects(10);
110         $t->get_ok('/redirect')->status_is(200)->content_like(qr/redirected/);
111
112         # Switch protocol from HTTP to HTTPS
113         $t->ua->server->url('https');
114         $t->get_ok('/secure')->status_is(200)->content_like(qr/secure/);
115
116         # Use absolute URL for request with Basic authentication
117         my $url = $t->ua->server->url->userinfo('sri:secr3t')->path('/secrets.json');
118         $t->post_ok($url => json => {limit => 10})
119           ->status_is(200)
120           ->json_is('/1/content', 'Mojo rocks!');
121
122         # Customize all transactions (including followed redirects)
123         $t->ua->on(start => sub {
124           my ($ua, $tx) = @_;
125           $tx->req->headers->accept_language('en-US');
126         });
127         $t->get_ok('/hello')->status_is(200)->content_like(qr/Howdy/);
128

METHODS

130       Test::Mojo inherits all methods from Mojo::Base and implements the
131       following new ones.
132
133   app
134         my $app = $t->app;
135         $t      = $t->app(Mojolicious->new);
136
137       Access application with "app" in Mojo::UserAgent::Server.
138
139         # Change log level
140         $t->app->log->level('fatal');
141
142         # Test application directly
143         is $t->app->defaults->{foo}, 'bar', 'right value';
144         ok $t->app->routes->find('echo')->is_websocket, 'WebSocket route';
145         my $c = $t->app->build_controller;
146         ok $c->render(template => 'foo'), 'rendering was successful';
147         is $c->res->status, 200, 'right status';
148         is $c->res->body, 'Foo!', 'right content';
149
150         # Change application behavior
151         $t->app->hook(before_dispatch => sub {
152           my $c = shift;
153           $c->render(text => 'This request did not reach the router.')
154             if $c->req->url->path->contains('/user');
155         });
156         $t->get_ok('/user')->status_is(200)->content_like(qr/not reach the router/);
157
158         # Extract additional information
159         my $stash;
160         $t->app->hook(after_dispatch => sub { $stash = shift->stash });
161         $t->get_ok('/hello')->status_is(200);
162         is $stash->{foo}, 'bar', 'right value';
163
164   content_is
165         $t = $t->content_is('working!');
166         $t = $t->content_is('working!', 'right content');
167
168       Check response content for exact match after retrieving it from "text"
169       in Mojo::Message.
170
171   content_isnt
172         $t = $t->content_isnt('working!');
173         $t = $t->content_isnt('working!', 'different content');
174
175       Opposite of "content_is".
176
177   content_like
178         $t = $t->content_like(qr/working!/);
179         $t = $t->content_like(qr/working!/, 'right content');
180
181       Check response content for similar match after retrieving it from
182       "text" in Mojo::Message.
183
184   content_type_is
185         $t = $t->content_type_is('text/html');
186         $t = $t->content_type_is('text/html', 'right content type');
187
188       Check response "Content-Type" header for exact match.
189
190   content_type_isnt
191         $t = $t->content_type_isnt('text/html');
192         $t = $t->content_type_isnt('text/html', 'different content type');
193
194       Opposite of "content_type_is".
195
196   content_type_like
197         $t = $t->content_type_like(qr/text/);
198         $t = $t->content_type_like(qr/text/, 'right content type');
199
200       Check response "Content-Type" header for similar match.
201
202   content_type_unlike
203         $t = $t->content_type_unlike(qr/text/);
204         $t = $t->content_type_unlike(qr/text/, 'different content type');
205
206       Opposite of "content_type_like".
207
208   content_unlike
209         $t = $t->content_unlike(qr/working!/);
210         $t = $t->content_unlike(qr/working!/, 'different content');
211
212       Opposite of "content_like".
213
214   delete_ok
215         $t = $t->delete_ok('http://example.com/foo');
216         $t = $t->delete_ok('/foo');
217         $t = $t->delete_ok('/foo' => {Accept => '*/*'} => 'Content!');
218         $t = $t->delete_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
219         $t = $t->delete_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
220
221       Perform a "DELETE" request and check for transport errors, takes the
222       same arguments as "delete" in Mojo::UserAgent, except for the callback.
223
224   element_count_is
225         $t = $t->element_count_is('div.foo[x=y]', 5);
226         $t = $t->element_count_is('html body div', 30, 'thirty elements');
227
228       Checks the number of HTML/XML elements matched by the CSS selector with
229       "find" in Mojo::DOM.
230
231   element_exists
232         $t = $t->element_exists('div.foo[x=y]');
233         $t = $t->element_exists('html head title', 'has a title');
234
235       Checks for existence of the CSS selectors first matching HTML/XML
236       element with "at" in Mojo::DOM.
237
238         # Check attribute values
239         $t->get_ok('/login')
240           ->element_exists('label[for=email]')
241           ->element_exists('input[name=email][type=text][value*="example.com"]')
242           ->element_exists('label[for=pass]')
243           ->element_exists('input[name=pass][type=password]')
244           ->element_exists('input[type=submit][value]');
245
246   element_exists_not
247         $t = $t->element_exists_not('div.foo[x=y]');
248         $t = $t->element_exists_not('html head title', 'has no title');
249
250       Opposite of "element_exists".
251
252   finish_ok
253         $t = $t->finish_ok;
254         $t = $t->finish_ok(1000);
255         $t = $t->finish_ok(1003 => 'Cannot accept data!');
256
257       Close WebSocket connection gracefully.
258
259   finished_ok
260         $t = $t->finished_ok(1000);
261
262       Wait for WebSocket connection to be closed gracefully and check status.
263
264   get_ok
265         $t = $t->get_ok('http://example.com/foo');
266         $t = $t->get_ok('/foo');
267         $t = $t->get_ok('/foo' => {Accept => '*/*'} => 'Content!');
268         $t = $t->get_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
269         $t = $t->get_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
270
271       Perform a "GET" request and check for transport errors, takes the same
272       arguments as "get" in Mojo::UserAgent, except for the callback.
273
274         # Run tests against remote host
275         $t->get_ok('https://mojolicious.org/perldoc')->status_is(200);
276
277         # Use relative URL for request with Basic authentication
278         $t->get_ok('//sri:secr3t@/secrets.json')
279           ->status_is(200)
280           ->json_is('/1/content', 'Mojo rocks!');
281
282         # Run additional tests on the transaction
283         $t->get_ok('/foo')->status_is(200);
284         is $t->tx->res->dom->at('input')->val, 'whatever', 'right value';
285
286   head_ok
287         $t = $t->head_ok('http://example.com/foo');
288         $t = $t->head_ok('/foo');
289         $t = $t->head_ok('/foo' => {Accept => '*/*'} => 'Content!');
290         $t = $t->head_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
291         $t = $t->head_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
292
293       Perform a "HEAD" request and check for transport errors, takes the same
294       arguments as "head" in Mojo::UserAgent, except for the callback.
295
296   header_is
297         $t = $t->header_is(ETag => '"abc321"');
298         $t = $t->header_is(ETag => '"abc321"', 'right header');
299
300       Check response header for exact match.
301
302   header_isnt
303         $t = $t->header_isnt(Etag => '"abc321"');
304         $t = $t->header_isnt(ETag => '"abc321"', 'different header');
305
306       Opposite of "header_is".
307
308   header_like
309         $t = $t->header_like(ETag => qr/abc/);
310         $t = $t->header_like(ETag => qr/abc/, 'right header');
311
312       Check response header for similar match.
313
314   header_unlike
315         $t = $t->header_unlike(ETag => qr/abc/);
316         $t = $t->header_unlike(ETag => qr/abc/, 'different header');
317
318       Opposite of "header_like".
319
320   json_has
321         $t = $t->json_has('/foo');
322         $t = $t->json_has('/minibar', 'has a minibar');
323
324       Check if JSON response contains a value that can be identified using
325       the given JSON Pointer with Mojo::JSON::Pointer.
326
327   json_hasnt
328         $t = $t->json_hasnt('/foo');
329         $t = $t->json_hasnt('/minibar', 'no minibar');
330
331       Opposite of "json_has".
332
333   json_is
334         $t = $t->json_is({foo => [1, 2, 3]});
335         $t = $t->json_is('/foo' => [1, 2, 3]);
336         $t = $t->json_is('/foo/1' => 2, 'right value');
337
338       Check the value extracted from JSON response using the given JSON
339       Pointer with Mojo::JSON::Pointer, which defaults to the root value if
340       it is omitted.
341
342   json_like
343         $t = $t->json_like('/foo/1' => qr/^\d+$/);
344         $t = $t->json_like('/foo/1' => qr/^\d+$/, 'right value');
345
346       Check the value extracted from JSON response using the given JSON
347       Pointer with Mojo::JSON::Pointer for similar match.
348
349   json_message_has
350         $t = $t->json_message_has('/foo');
351         $t = $t->json_message_has('/minibar', 'has a minibar');
352
353       Check if JSON WebSocket message contains a value that can be identified
354       using the given JSON Pointer with Mojo::JSON::Pointer.
355
356   json_message_hasnt
357         $t = $t->json_message_hasnt('/foo');
358         $t = $t->json_message_hasnt('/minibar', 'no minibar');
359
360       Opposite of "json_message_has".
361
362   json_message_is
363         $t = $t->json_message_is({foo => [1, 2, 3]});
364         $t = $t->json_message_is('/foo' => [1, 2, 3]);
365         $t = $t->json_message_is('/foo/1' => 2, 'right value');
366
367       Check the value extracted from JSON WebSocket message using the given
368       JSON Pointer with Mojo::JSON::Pointer, which defaults to the root value
369       if it is omitted.
370
371   json_message_like
372         $t = $t->json_message_like('/foo/1' => qr/^\d+$/);
373         $t = $t->json_message_like('/foo/1' => qr/^\d+$/, 'right value');
374
375       Check the value extracted from JSON WebSocket message using the given
376       JSON Pointer with Mojo::JSON::Pointer for similar match.
377
378   json_message_unlike
379         $t = $t->json_message_unlike('/foo/1' => qr/^\d+$/);
380         $t = $t->json_message_unlike('/foo/1' => qr/^\d+$/, 'different value');
381
382       Opposite of "json_message_like".
383
384   json_unlike
385         $t = $t->json_unlike('/foo/1' => qr/^\d+$/);
386         $t = $t->json_unlike('/foo/1' => qr/^\d+$/, 'different value');
387
388       Opposite of "json_like".
389
390   message_is
391         $t = $t->message_is({binary => $bytes});
392         $t = $t->message_is({text   => $bytes});
393         $t = $t->message_is('working!');
394         $t = $t->message_is('working!', 'right message');
395
396       Check WebSocket message for exact match.
397
398   message_isnt
399         $t = $t->message_isnt({binary => $bytes});
400         $t = $t->message_isnt({text   => $bytes});
401         $t = $t->message_isnt('working!');
402         $t = $t->message_isnt('working!', 'different message');
403
404       Opposite of "message_is".
405
406   message_like
407         $t = $t->message_like({binary => qr/$bytes/});
408         $t = $t->message_like({text   => qr/$bytes/});
409         $t = $t->message_like(qr/working!/);
410         $t = $t->message_like(qr/working!/, 'right message');
411
412       Check WebSocket message for similar match.
413
414   message_ok
415         $t = $t->message_ok;
416         $t = $t->message_ok('got a message');
417
418       Wait for next WebSocket message to arrive.
419
420         # Wait for message and perform multiple tests on it
421         $t->websocket_ok('/time')
422           ->message_ok
423           ->message_like(qr/\d+/)
424           ->message_unlike(qr/\w+/)
425           ->finish_ok;
426
427   message_unlike
428         $t = $t->message_unlike({binary => qr/$bytes/});
429         $t = $t->message_unlike({text   => qr/$bytes/});
430         $t = $t->message_unlike(qr/working!/);
431         $t = $t->message_unlike(qr/working!/, 'different message');
432
433       Opposite of "message_like".
434
435   new
436         my $t = Test::Mojo->new;
437         my $t = Test::Mojo->new('MyApp');
438         my $t = Test::Mojo->new('MyApp', {foo => 'bar'});
439         my $t = Test::Mojo->new(Mojo::File->new('/path/to/myapp.pl'));
440         my $t = Test::Mojo->new(Mojo::File->new('/path/to/myapp.pl'), {foo => 'bar'});
441         my $t = Test::Mojo->new(MyApp->new);
442         my $t = Test::Mojo->new(MyApp->new, {foo => 'bar'});
443
444       Construct a new Test::Mojo object. In addition to a class name or
445       Mojo::File object pointing to the application script, you can pass
446       along a hash reference with configuration values that will be used to
447       override the application configuration. The special configuration value
448       "config_override" will be set in "config" in Mojolicious as well, which
449       is used to disable configuration plugins like
450       Mojolicious::Plugin::Config and Mojolicious::Plugin::JSONConfig for
451       tests.
452
453         # Load application script relative to the "t" directory
454         use Mojo::File 'path';
455         my $t = Test::Mojo->new(path(__FILE__)->dirname->sibling('myapp.pl'));
456
457   options_ok
458         $t = $t->options_ok('http://example.com/foo');
459         $t = $t->options_ok('/foo');
460         $t = $t->options_ok('/foo' => {Accept => '*/*'} => 'Content!');
461         $t = $t->options_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
462         $t = $t->options_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
463
464       Perform a "OPTIONS" request and check for transport errors, takes the
465       same arguments as "options" in Mojo::UserAgent, except for the
466       callback.
467
468   or
469         $t = $t->or(sub {...});
470
471       Execute callback if the value of "success" is false.
472
473         # Diagnostics
474         $t->get_ok('/bad')->or(sub { diag 'Must have been Glen!' })
475           ->status_is(200)->or(sub { diag $t->tx->res->dom->at('title')->text });
476
477   patch_ok
478         $t = $t->patch_ok('http://example.com/foo');
479         $t = $t->patch_ok('/foo');
480         $t = $t->patch_ok('/foo' => {Accept => '*/*'} => 'Content!');
481         $t = $t->patch_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
482         $t = $t->patch_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
483
484       Perform a "PATCH" request and check for transport errors, takes the
485       same arguments as "patch" in Mojo::UserAgent, except for the callback.
486
487   post_ok
488         $t = $t->post_ok('http://example.com/foo');
489         $t = $t->post_ok('/foo');
490         $t = $t->post_ok('/foo' => {Accept => '*/*'} => 'Content!');
491         $t = $t->post_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
492         $t = $t->post_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
493
494       Perform a "POST" request and check for transport errors, takes the same
495       arguments as "post" in Mojo::UserAgent, except for the callback.
496
497         # Test file upload
498         my $upload = {foo => {content => 'bar', filename => 'baz.txt'}};
499         $t->post_ok('/upload' => form => $upload)->status_is(200);
500
501         # Test JSON API
502         $t->post_ok('/hello.json' => json => {hello => 'world'})
503           ->status_is(200)
504           ->json_is({bye => 'world'});
505
506   put_ok
507         $t = $t->put_ok('http://example.com/foo');
508         $t = $t->put_ok('/foo');
509         $t = $t->put_ok('/foo' => {Accept => '*/*'} => 'Content!');
510         $t = $t->put_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
511         $t = $t->put_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
512
513       Perform a "PUT" request and check for transport errors, takes the same
514       arguments as "put" in Mojo::UserAgent, except for the callback.
515
516   request_ok
517         $t = $t->request_ok(Mojo::Transaction::HTTP->new);
518
519       Perform request and check for transport errors.
520
521         # Request with custom method
522         my $tx = $t->ua->build_tx(FOO => '/test.json' => json => {foo => 1});
523         $t->request_ok($tx)->status_is(200)->json_is({success => 1});
524
525         # Request with custom cookie
526         my $tx = $t->ua->build_tx(GET => '/account');
527         $tx->req->cookies({name => 'user', value => 'sri'});
528         $t->request_ok($tx)->status_is(200)->text_is('head > title' => 'Hello sri');
529
530         # Custom WebSocket handshake
531         my $tx = $t->ua->build_websocket_tx('/foo');
532         $tx->req->headers->remove('User-Agent');
533         $t->request_ok($tx)->message_ok->message_is('bar')->finish_ok;
534
535   reset_session
536         $t = $t->reset_session;
537
538       Reset user agent session.
539
540   send_ok
541         $t = $t->send_ok({binary => $bytes});
542         $t = $t->send_ok({text   => $bytes});
543         $t = $t->send_ok({json   => {test => [1, 2, 3]}});
544         $t = $t->send_ok([$fin, $rsv1, $rsv2, $rsv3, $op, $payload]);
545         $t = $t->send_ok($chars);
546         $t = $t->send_ok($chars, 'sent successfully');
547
548       Send message or frame via WebSocket.
549
550         # Send JSON object as "Text" message
551         $t->websocket_ok('/echo.json')
552           ->send_ok({json => {test => 'I ♥ Mojolicious!'}})
553           ->message_ok
554           ->json_message_is('/test' => 'I ♥ Mojolicious!')
555           ->finish_ok;
556
557   status_is
558         $t = $t->status_is(200);
559         $t = $t->status_is(200, 'right status');
560
561       Check response status for exact match.
562
563   status_isnt
564         $t = $t->status_isnt(200);
565         $t = $t->status_isnt(200, 'different status');
566
567       Opposite of "status_is".
568
569   text_is
570         $t = $t->text_is('div.foo[x=y]' => 'Hello!');
571         $t = $t->text_is('html head title' => 'Hello!', 'right title');
572
573       Checks text content of the CSS selectors first matching HTML/XML
574       element for exact match with "at" in Mojo::DOM.
575
576   text_isnt
577         $t = $t->text_isnt('div.foo[x=y]' => 'Hello!');
578         $t = $t->text_isnt('html head title' => 'Hello!', 'different title');
579
580       Opposite of "text_is".
581
582   text_like
583         $t = $t->text_like('div.foo[x=y]' => qr/Hello/);
584         $t = $t->text_like('html head title' => qr/Hello/, 'right title');
585
586       Checks text content of the CSS selectors first matching HTML/XML
587       element for similar match with "at" in Mojo::DOM.
588
589   text_unlike
590         $t = $t->text_unlike('div.foo[x=y]' => qr/Hello/);
591         $t = $t->text_unlike('html head title' => qr/Hello/, 'different title');
592
593       Opposite of "text_like".
594
595   websocket_ok
596         $t = $t->websocket_ok('http://example.com/echo');
597         $t = $t->websocket_ok('/echo');
598         $t = $t->websocket_ok('/echo' => {DNT => 1} => ['v1.proto']);
599
600       Open a WebSocket connection with transparent handshake, takes the same
601       arguments as "websocket" in Mojo::UserAgent, except for the callback.
602
603         # WebSocket with permessage-deflate compression
604         $t->websocket_ok('/' => {'Sec-WebSocket-Extensions' => 'permessage-deflate'})
605           ->send_ok('y' x 50000)
606           ->message_ok
607           ->message_is('z' x 50000)
608           ->finish_ok;
609

SEE ALSO

611       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
612
613
614
615perl v5.28.0                      2018-09-09                     Test::Mojo(3)
Impressum