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_exists
297         $t = $t->header_exists('ETag');
298         $t = $t->header_exists('ETag', 'header exists');
299
300       Check if response header exists.
301
302   header_exists_not
303         $t = $t->header_exists_not('ETag');
304         $t = $t->header_exists_not('ETag', 'header is missing');
305
306       Opposite of "header_exists".
307
308   header_is
309         $t = $t->header_is(ETag => '"abc321"');
310         $t = $t->header_is(ETag => '"abc321"', 'right header');
311
312       Check response header for exact match.
313
314   header_isnt
315         $t = $t->header_isnt(Etag => '"abc321"');
316         $t = $t->header_isnt(ETag => '"abc321"', 'different header');
317
318       Opposite of "header_is".
319
320   header_like
321         $t = $t->header_like(ETag => qr/abc/);
322         $t = $t->header_like(ETag => qr/abc/, 'right header');
323
324       Check response header for similar match.
325
326   header_unlike
327         $t = $t->header_unlike(ETag => qr/abc/);
328         $t = $t->header_unlike(ETag => qr/abc/, 'different header');
329
330       Opposite of "header_like".
331
332   json_has
333         $t = $t->json_has('/foo');
334         $t = $t->json_has('/minibar', 'has a minibar');
335
336       Check if JSON response contains a value that can be identified using
337       the given JSON Pointer with Mojo::JSON::Pointer.
338
339   json_hasnt
340         $t = $t->json_hasnt('/foo');
341         $t = $t->json_hasnt('/minibar', 'no minibar');
342
343       Opposite of "json_has".
344
345   json_is
346         $t = $t->json_is({foo => [1, 2, 3]});
347         $t = $t->json_is('/foo' => [1, 2, 3]);
348         $t = $t->json_is('/foo/1' => 2, 'right value');
349
350       Check the value extracted from JSON response using the given JSON
351       Pointer with Mojo::JSON::Pointer, which defaults to the root value if
352       it is omitted.
353
354   json_like
355         $t = $t->json_like('/foo/1' => qr/^\d+$/);
356         $t = $t->json_like('/foo/1' => qr/^\d+$/, 'right value');
357
358       Check the value extracted from JSON response using the given JSON
359       Pointer with Mojo::JSON::Pointer for similar match.
360
361   json_message_has
362         $t = $t->json_message_has('/foo');
363         $t = $t->json_message_has('/minibar', 'has a minibar');
364
365       Check if JSON WebSocket message contains a value that can be identified
366       using the given JSON Pointer with Mojo::JSON::Pointer.
367
368   json_message_hasnt
369         $t = $t->json_message_hasnt('/foo');
370         $t = $t->json_message_hasnt('/minibar', 'no minibar');
371
372       Opposite of "json_message_has".
373
374   json_message_is
375         $t = $t->json_message_is({foo => [1, 2, 3]});
376         $t = $t->json_message_is('/foo' => [1, 2, 3]);
377         $t = $t->json_message_is('/foo/1' => 2, 'right value');
378
379       Check the value extracted from JSON WebSocket message using the given
380       JSON Pointer with Mojo::JSON::Pointer, which defaults to the root value
381       if it is omitted.
382
383   json_message_like
384         $t = $t->json_message_like('/foo/1' => qr/^\d+$/);
385         $t = $t->json_message_like('/foo/1' => qr/^\d+$/, 'right value');
386
387       Check the value extracted from JSON WebSocket message using the given
388       JSON Pointer with Mojo::JSON::Pointer for similar match.
389
390   json_message_unlike
391         $t = $t->json_message_unlike('/foo/1' => qr/^\d+$/);
392         $t = $t->json_message_unlike('/foo/1' => qr/^\d+$/, 'different value');
393
394       Opposite of "json_message_like".
395
396   json_unlike
397         $t = $t->json_unlike('/foo/1' => qr/^\d+$/);
398         $t = $t->json_unlike('/foo/1' => qr/^\d+$/, 'different value');
399
400       Opposite of "json_like".
401
402   message_is
403         $t = $t->message_is({binary => $bytes});
404         $t = $t->message_is({text   => $bytes});
405         $t = $t->message_is('working!');
406         $t = $t->message_is('working!', 'right message');
407
408       Check WebSocket message for exact match.
409
410   message_isnt
411         $t = $t->message_isnt({binary => $bytes});
412         $t = $t->message_isnt({text   => $bytes});
413         $t = $t->message_isnt('working!');
414         $t = $t->message_isnt('working!', 'different message');
415
416       Opposite of "message_is".
417
418   message_like
419         $t = $t->message_like({binary => qr/$bytes/});
420         $t = $t->message_like({text   => qr/$bytes/});
421         $t = $t->message_like(qr/working!/);
422         $t = $t->message_like(qr/working!/, 'right message');
423
424       Check WebSocket message for similar match.
425
426   message_ok
427         $t = $t->message_ok;
428         $t = $t->message_ok('got a message');
429
430       Wait for next WebSocket message to arrive.
431
432         # Wait for message and perform multiple tests on it
433         $t->websocket_ok('/time')
434           ->message_ok
435           ->message_like(qr/\d+/)
436           ->message_unlike(qr/\w+/)
437           ->finish_ok;
438
439   message_unlike
440         $t = $t->message_unlike({binary => qr/$bytes/});
441         $t = $t->message_unlike({text   => qr/$bytes/});
442         $t = $t->message_unlike(qr/working!/);
443         $t = $t->message_unlike(qr/working!/, 'different message');
444
445       Opposite of "message_like".
446
447   new
448         my $t = Test::Mojo->new;
449         my $t = Test::Mojo->new('MyApp');
450         my $t = Test::Mojo->new('MyApp', {foo => 'bar'});
451         my $t = Test::Mojo->new(Mojo::File->new('/path/to/myapp.pl'));
452         my $t = Test::Mojo->new(Mojo::File->new('/path/to/myapp.pl'), {foo => 'bar'});
453         my $t = Test::Mojo->new(MyApp->new);
454         my $t = Test::Mojo->new(MyApp->new, {foo => 'bar'});
455
456       Construct a new Test::Mojo object. In addition to a class name or
457       Mojo::File object pointing to the application script, you can pass
458       along a hash reference with configuration values that will be used to
459       override the application configuration. The special configuration value
460       "config_override" will be set in "config" in Mojolicious as well, which
461       is used to disable configuration plugins like
462       Mojolicious::Plugin::Config and Mojolicious::Plugin::JSONConfig for
463       tests.
464
465         # Load application script relative to the "t" directory
466         use Mojo::File 'path';
467         my $t = Test::Mojo->new(path(__FILE__)->dirname->sibling('myapp.pl'));
468
469   options_ok
470         $t = $t->options_ok('http://example.com/foo');
471         $t = $t->options_ok('/foo');
472         $t = $t->options_ok('/foo' => {Accept => '*/*'} => 'Content!');
473         $t = $t->options_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
474         $t = $t->options_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
475
476       Perform a "OPTIONS" request and check for transport errors, takes the
477       same arguments as "options" in Mojo::UserAgent, except for the
478       callback.
479
480   or
481         $t = $t->or(sub {...});
482
483       Execute callback if the value of "success" is false.
484
485         # Diagnostics
486         $t->get_ok('/bad')->or(sub { diag 'Must have been Glen!' })
487           ->status_is(200)->or(sub { diag $t->tx->res->dom->at('title')->text });
488
489   patch_ok
490         $t = $t->patch_ok('http://example.com/foo');
491         $t = $t->patch_ok('/foo');
492         $t = $t->patch_ok('/foo' => {Accept => '*/*'} => 'Content!');
493         $t = $t->patch_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
494         $t = $t->patch_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
495
496       Perform a "PATCH" request and check for transport errors, takes the
497       same arguments as "patch" in Mojo::UserAgent, except for the callback.
498
499   post_ok
500         $t = $t->post_ok('http://example.com/foo');
501         $t = $t->post_ok('/foo');
502         $t = $t->post_ok('/foo' => {Accept => '*/*'} => 'Content!');
503         $t = $t->post_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
504         $t = $t->post_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
505
506       Perform a "POST" request and check for transport errors, takes the same
507       arguments as "post" in Mojo::UserAgent, except for the callback.
508
509         # Test file upload
510         my $upload = {foo => {content => 'bar', filename => 'baz.txt'}};
511         $t->post_ok('/upload' => form => $upload)->status_is(200);
512
513         # Test JSON API
514         $t->post_ok('/hello.json' => json => {hello => 'world'})
515           ->status_is(200)
516           ->json_is({bye => 'world'});
517
518   put_ok
519         $t = $t->put_ok('http://example.com/foo');
520         $t = $t->put_ok('/foo');
521         $t = $t->put_ok('/foo' => {Accept => '*/*'} => 'Content!');
522         $t = $t->put_ok('/foo' => {Accept => '*/*'} => form => {a => 'b'});
523         $t = $t->put_ok('/foo' => {Accept => '*/*'} => json => {a => 'b'});
524
525       Perform a "PUT" request and check for transport errors, takes the same
526       arguments as "put" in Mojo::UserAgent, except for the callback.
527
528   request_ok
529         $t = $t->request_ok(Mojo::Transaction::HTTP->new);
530
531       Perform request and check for transport errors.
532
533         # Request with custom method
534         my $tx = $t->ua->build_tx(FOO => '/test.json' => json => {foo => 1});
535         $t->request_ok($tx)->status_is(200)->json_is({success => 1});
536
537         # Request with custom cookie
538         my $tx = $t->ua->build_tx(GET => '/account');
539         $tx->req->cookies({name => 'user', value => 'sri'});
540         $t->request_ok($tx)->status_is(200)->text_is('head > title' => 'Hello sri');
541
542         # Custom WebSocket handshake
543         my $tx = $t->ua->build_websocket_tx('/foo');
544         $tx->req->headers->remove('User-Agent');
545         $t->request_ok($tx)->message_ok->message_is('bar')->finish_ok;
546
547   reset_session
548         $t = $t->reset_session;
549
550       Reset user agent session.
551
552   send_ok
553         $t = $t->send_ok({binary => $bytes});
554         $t = $t->send_ok({text   => $bytes});
555         $t = $t->send_ok({json   => {test => [1, 2, 3]}});
556         $t = $t->send_ok([$fin, $rsv1, $rsv2, $rsv3, $op, $payload]);
557         $t = $t->send_ok($chars);
558         $t = $t->send_ok($chars, 'sent successfully');
559
560       Send message or frame via WebSocket.
561
562         # Send JSON object as "Text" message
563         $t->websocket_ok('/echo.json')
564           ->send_ok({json => {test => 'I ♥ Mojolicious!'}})
565           ->message_ok
566           ->json_message_is('/test' => 'I ♥ Mojolicious!')
567           ->finish_ok;
568
569   status_is
570         $t = $t->status_is(200);
571         $t = $t->status_is(200, 'right status');
572
573       Check response status for exact match.
574
575   status_isnt
576         $t = $t->status_isnt(200);
577         $t = $t->status_isnt(200, 'different status');
578
579       Opposite of "status_is".
580
581   text_is
582         $t = $t->text_is('div.foo[x=y]' => 'Hello!');
583         $t = $t->text_is('html head title' => 'Hello!', 'right title');
584
585       Checks text content of the CSS selectors first matching HTML/XML
586       element for exact match with "at" in Mojo::DOM.
587
588   text_isnt
589         $t = $t->text_isnt('div.foo[x=y]' => 'Hello!');
590         $t = $t->text_isnt('html head title' => 'Hello!', 'different title');
591
592       Opposite of "text_is".
593
594   text_like
595         $t = $t->text_like('div.foo[x=y]' => qr/Hello/);
596         $t = $t->text_like('html head title' => qr/Hello/, 'right title');
597
598       Checks text content of the CSS selectors first matching HTML/XML
599       element for similar match with "at" in Mojo::DOM.
600
601   text_unlike
602         $t = $t->text_unlike('div.foo[x=y]' => qr/Hello/);
603         $t = $t->text_unlike('html head title' => qr/Hello/, 'different title');
604
605       Opposite of "text_like".
606
607   websocket_ok
608         $t = $t->websocket_ok('http://example.com/echo');
609         $t = $t->websocket_ok('/echo');
610         $t = $t->websocket_ok('/echo' => {DNT => 1} => ['v1.proto']);
611
612       Open a WebSocket connection with transparent handshake, takes the same
613       arguments as "websocket" in Mojo::UserAgent, except for the callback.
614
615         # WebSocket with permessage-deflate compression
616         $t->websocket_ok('/' => {'Sec-WebSocket-Extensions' => 'permessage-deflate'})
617           ->send_ok('y' x 50000)
618           ->message_ok
619           ->message_is('z' x 50000)
620           ->finish_ok;
621

SEE ALSO

623       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
624
625
626
627perl v5.30.0                      2019-07-26                     Test::Mojo(3)
Impressum