• Stars
    star
    411
  • Rank 105,247 (Top 3 %)
  • Language
    JavaScript
  • Created almost 14 years ago
  • Updated over 12 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tobi: Expressive server-side functional testing with jQuery

Tobi

Expressive server-side functional testing with jQuery and jsdom.

Tobi allows you to test your web application as if it were a browser. Interactions with your app are performed via jsdom, htmlparser, and jQuery, in combination with Tobi's Cookie Jar, provides a natural JavaScript API for traversing, manipulating and asserting the DOM, and session based browsing.

Example

In the example below, we have an http server or express app require()ed, and we simply create new tobi Browser for that app to test against. Then we GET /login, receiving a response to assert headers, status codes etc, and the $ jQuery context.

We can then use regular css selectors to grab the form, we use tobi's .fill() method to fill some inputs (supports textareas, checkboxes, radios, etc), then we proceed to submitting the form, again receiving a response and the jQuery context.

var tobi = require('tobi')
  , app = require('./my/app')
  , browser = tobi.createBrowser(app);

browser.get('/login', function(res, $){
  $('form')
    .fill({ username: 'tj', password: 'tobi' })
    .submit(function(res, $){
      res.should.have.status(200);
      res.should.have.header('Content-Length');
      res.should.have.header('Content-Type', 'text/html; charset=utf-8');
      $('ul.messages').should.have.one('li', 'Successfully authenticated');
      browser.get('/login', function(res, $){
        res.should.have.status(200);
        $('ul.messages').should.have.one('li', 'Already authenticated');
        // We are finished testing, close the server
        app.close();
      });
    });
});

Browser

Tobi provides the Browser object, created via tobi.createBrowser(app), where app is a node http.Server, so for example Connect or Express apps will work just fine. There is no need to invoke listen() as this is handled by Tobi, and requests will be deferred until the server is listening.

Alternatively you may pass a port and host to createBrowser(), for example:

var browser = tobi.createBrowser(80, 'lb.dev'); 

Evaluate External Resources

To evaluate script tags simply pass the { external: true } option:

var browser = tobi.createBrowser(app, { external: true });

Browser#get()

Perform a GET request with optional options containing headers, etc:

browser.get('/login', function(res, $){
  
});

With options:

browser.get('/login', { headers: { ... }}, function(res, $){
  
});

Aliased as visit, and open.

Browser#post()

Perform a POST request with optional options containing headers, body etc:

browser.post('/login', function(res, $){
  
});

With options:

browser.post('/login', { body: 'foo=bar' }, function(res, $){
  
});

Browser#back()

GET the previous page:

browser.get('/', function(){
  // on /
  browser.get('/foo', function(){
    // on /foo
    browser.back(function(){
      // on /
    });
  });
});

Browser locators

Locators are extended extend selectors, the rules are as following:

  • element text
  • element id
  • element value
  • css selector

These rules apply to all Browser related methods such as click(), fill(), type() etc. Provided the following markup:

<form>
  <input id="form-login" type="submit" value="Login" />
</form>

The following locators will match the input:

.click('Login');
.click('form-login');
.click('input[type=submit]');
.click(':submit');

Browser#click(locator[, fn])

Tobi allows you to click() a elements, button[type=submit] elements, and input[type=submit] elements in order to submit a form, or request a url.

Submitting a form:

browser.click('Login', function(res, $){
  
});

Submitting with jQuery (no locators):

$('form :submit').click(function(res, $){
  
});

Clicking a link:

browser.click('Register Account', function(res, $){
  
});

Clicking with jQuery (no locators):

$('a.register', function(res, $){
  
});

Browser#submit(locator|fn, fn)

Submit the first form in context:

browser.submit(function(res, $){
  
});

browser.submit(function(){
  
});

Browser#type(locator, str)

"Type" the given str:

browser
  .type('username', 'tj') 
  .type('password', 'foobar');

Browser#{check,uncheck}(locator)

Check or uncheck the given locator:

browser
  .check('agreement')
  .uncheck('agreement');

Browser#select(locator, options)

Select the given option or options:

browser
  .select('colors', 'Red')
  .select('colors', ['Red', 'Green']);

Browser#fill(locator, fields)

Fill the given fields, supporting all types of inputs. For example we might have the following form:

<form>
  <input type="text" name="user[name]" />
  <input type="text" name="user[email]" />
  <input type="checkbox" name="user[agreement]" />
  
  <select name="digest">
    <option value="none">Never</option>
    <option value="daily">Daily</option>
    <option value="weekly">Weekly</option>
  </select>
  
  <select name="favorite-colors" multiple>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
  </select>
</form> 

Which can be filled using locators:

browser
  .fill({
      'user[name]': 'tj'
    , 'user[email]': '[email protected]'
    , 'user[agreement]': true
    , 'user[digest]': 'Daily'
    , 'user[favorite-colors]': ['red', 'Green']
  }).submit(function(){
    
  });

With jQuery:

$('form')
  .fill({
      'user[name]': 'tj'
    , 'user[favorite-colors]': 'red'
  }).submit(function(){
    
  });

Browser#text(locator)

Return text at the given locator. For example if we have the form option somewhere in our markup:

<option value="once">Once per day</option>

We can invoke browser.text('once') returning "Once per day".

Browser#{context,within}(selector, fn)

Alter the browser context for the duration of the given callback fn. For example if you have several forms on a page, an wish to focus on one:

<div><form id="user-search" method="post" action="/search/users">
  <input type="text" name="query" />
</form></div>

<div><form id="post-search" method="post" action="/search/posts">
  <input type="text" name="query" />
</form></div>

Example test using contexts:

browser.get('/search', function(res, $){

  // Global context has 2 forms
  $('form').should.have.length(2);

  // Focus on the second div
  browser.within('div:nth-child(2)', function(){

    // We now have one form, and no direct input children
    $('> form').should.have.length(1);
    $('> input').should.have.length(0);

    // Focus on the form, we now have a single direct input child
    browser.within('form', function(){
      $('> form').should.have.length(0);
      $('> input').should.have.length(1);
    });

    // Back to our div focus, we have one form again
    $('> form').should.have.length(1);
    $('> input').should.have.length(0);

    // Methods such as .type() etc work with contexts
    browser
    .type('query', 'foo bar')
    .submit(function(res){

    });
  });

  // Back to global context
  $('form').should.have.length(2);
});

Assertions

Tobi extends the should.js assertion library to provide you with DOM and response related assertion methods.

Assertion#text(str|regexp)

Assert element text via regexp or string:

  elem.should.have.text('foo bar');
  elem.should.have.text(/^foo/);
  elem.should.not.have.text('rawr');

When asserting a descendant's text amongst a heap of elements, we can utilize the .include modifier:

  $('*').should.include.text('My Site');

Assertion#many(selector)

Assert that one or more of the given selector is present:

  ul.should.have.many('li');

Assertion#one(selector)

Assert that one of the given selector is present:

  p.should.have.one('input');

Assertion#attr(key[, val])

Assert that the given key exists, with optional val:

  p.should.not.have.attr('href');
  a.should.have.attr('href');
  a.should.have.attr('href', 'http://learnboost.com');

Shortcuts are also provided:

- id()
- title()
- href()
- alt()
- src()
- rel()
- media()
- name()
- action()
- method()
- value()
- enabled
- disabled
- checked
- selected

For example:

  form.should.have.id('user-edit');
  form.should.have.action('/login');
  form.should.have.method('post');
  checkbox.should.be.enabled;
  checkbox.should.be.disabled;
  option.should.be.selected;
  option.should.not.be.selected;

Assertion#class(name)

Assert that the element has the given class name.

  form.should.have.class('user-edit');

Assertion#status(code)

Assert response status code:

  res.should.have.status(200);
  res.should.not.have.status(500);

Assertion#header(field[, val])

Assert presence of response header field and optional val:

  res.should.have.header('Content-Length');
  res.should.have.header('Content-Type', 'text/html');

Testing

Install the deps:

$ npm install

and execute:

$ make test

WWTD

What Would Tobi Do:

Tobi

License

(The MIT License)

Copyright (c) 2010 LearnBoost <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation te rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

cluster

Node.JS multi-core server manager with plugins support.
JavaScript
2,292
star
2

up

Zero-downtime reloads and requests load balancer based on distribute.
JavaScript
540
star
3

soda

Selenium Node.JS adapter
JavaScript
466
star
4

express-mongoose

Plugin for easy rendering of Mongoose async Query results.
JavaScript
451
star
5

websocket.io

JavaScript
329
star
6

console-trace

Adds a handy `trace` flag to the console object to prepend the file and line number.
JavaScript
296
star
7

socket.io-spec

Specification for the Socket.IO Protocol (0.9)
225
star
8

distribute

Distribute is a middleware-based API to expressively perform request routing / load balancing in Node.JS.
JavaScript
219
star
9

nodestream

Realtime apps made easy with templating
JavaScript
219
star
10

superagent-oauth

node-oauth signing plugin for superagent requests
JavaScript
87
star
11

shorty

LearnBoost URL shortening/redirection service.
JavaScript
79
star
12

CSS3-Overlay

A CSS3 Overlay system for modal dialogs.
65
star
13

up-hook

UP middleware to enable seamless zero-downtime HTTP server reloads upon GitHub post-receive webhooks.
JavaScript
51
star
14

jadevu

Minimal precompiled Jade templates exposed to the client.
JavaScript
50
star
15

texty

Canvas text
JavaScript
48
star
16

Socket.IO-node-client

[WIP] Socket.IO 0.7 Node.JS client implementation, with simulated browser transports
JavaScript
43
star
17

drawback

The Drawback framework provides a seamless way to render 2D drawings on the client side using HTML5 technologies with a server-side backend.
JavaScript
38
star
18

stylus

Placeholder repo for keeping Stylus docs in place
34
star
19

connect-timeout

Requests timeout middleware
JavaScript
32
star
20

socket.io-node

32
star
21

cfg.js

Minimal Node.JS configuration interface with support for overrides, environments and inheritance.
JavaScript
30
star
22

cluster-mail

Cluster exceptions in your inbox
JavaScript
26
star
23

superagent-queue

Adds request queueing capabilities to superagent
JavaScript
18
star
24

cluster-log

Advanced logging plugin for cluster
JavaScript
15
star
25

engine.io-flash

1
star