Code Monkey home page Code Monkey logo

mithril-query's Introduction

mithril-query

Gitter Build Status rethink.js js-standard-style

Query mithril virtual dom for testing purposes

Installation

npm install mithril-query --save-dev

Setup

In order to run tests in mithril 1.0 we need to do some setup. That is to mock the dom for the mithril render and request modules. This can be done by requiring a 'setup' file in your 'mocha' tests with the following contents.

global.window = Object.assign(require('mithril/test-utils/domMock.js')(), require('mithril/test-utils/pushStateMock')())

Usage

You can run this tests serverside or use browserify and run them in browsers.

// simple module: simple.js
var m = require('mithril')

module.exports = {
  view: function () {
    return m('div', [
      m('span', 'spanContent'),
      m('#fooId', 'fooContent'),
      m('.barClass', 'barContent')
    ])
  }
}
// test for simple module: simple.test.js
/* eslint-env mocha */
global.window = Object.assign(require('mithril/test-utils/domMock.js')(), require('mithril/test-utils/pushStateMock')())
var simpleModule = require('./simple')
var mq = require('mithril-query')

describe('simple module', function () {
  it('should generate appropriate output', function () {
    var output = mq(simpleModule)
    output.should.have('span')
    output.should.have('div > span')
    output.should.have('#fooId')
    output.should.have('.barClass')
    output.should.have('.barClass:contains(barContent)')
    output.should.contain('barContent')
  })
})

Run the test with

mocha simple.test.js

API

Initialise

First call mithril-query with either a vnode or a component. You can call it with one extra argument wich will be used as attrs in the component case. Closure Components are currently only supported as part of the tree, not directly as argumend to mq function. Supporting this will result in a breaking change, because it conflicts with the call with a view function as first argument, what is deprecated now.

var mq = require('mithril-query')

// plain vnode
var out = mq(m('div'))

// view function - DEPRECATED! don't use.
function myView(text) {
  return m('div', text)
}
var out = mq(myView, 'huhu')

// Use this instead!
var out = mq({
  view: () => myView('huhu')
})

// component
var myComponent = {
  view: function (vnode) {
    return m('div', vnode.attrs.text)
  }
}
var out = mq(myComponent, { text: 'huhu' })

Query API

As you can see mq returns an out-Object which has the following query-API. We use cssauron as engine, so look there if you want to see, what selectors are possible.

  • out.first(selector) – Returns the first element that matches the selector.
  • out.find(selector) – Returns all elements that match the selector.
  • out.has(selector) –  Returns true if any element in tree matches the selector, otherwise false.
  • out.contains(string) – Returns true if any element in tree contains the string, otherwise false.
  • out.log(selector, [logFN]) – Small helper function to log out what was selected. Mainly for debugging purposes. You can give an optional function which is called with the result. It defaults to console.log.

You can use these nice assertions. They throw errors if they're not fullfiled. See the example in the example folder.

  • out.should.have([count], selector)

Throws if no element is found with selector. If count is given, it throws if count does not match.

  • out.should.not.have(selector) – Throws if an element is found with selector.
  • out.should.have.at.least(count, selector) – Throws if there a fewer than count elements matching the selector
  • out.should.have([selector0, selector1, selector2]) – Throws there aren't at least one element for each selector.
  • out.should.contain(string) – Throws if no element contains string.
  • out.should.not.contain(string) - Throws if any element contains string.

Event triggering

It is also possible to trigger element events like onfocus and onclick and set values on <input>-fields. This allows you to write "integration tests" that run also on serverside.

Attention: Currently there is no event bubbleing supported.

  • out.click(selector, [event], [silent]) – Runs onclick for first element that matches selector. Optional event is given as event. Options silent-Flag signals that no redraw should happen. event.redraw = false is respected.
  • out.setValue(selector, string, [silent]) – Runs oninput and onchange for first element that matches selector. Event contains the value as event.target.value and event.target.currentValue.
  • out.trigger(selector, eventname, [event], [silent]) – General purpose event triggerer. Calls eventname on first matching element giving event as event.

It also supports key events

  • out.keydown(selector, keycode, [event]) – calls onkeydown with keycode
  • out.keydown(selector, keyname, [event]) – calse onkeydown with keycode mapped from name. Mapping is done with this lib.

keyup, keypress are supported as well.

Auto "Redrawing"

You can also use auto rendering like mithril does. If you call the query function with a module, it instantiates the module the same way as mithril does. When using one of the upper events, redraw of the view is automatically called.

Example:

  // module code
  var module = {
    oninit: function (vnode) {
      vnode.state = {
        visible: true,
        toggleMe: function () { vnode.state.visible = !vnode.state.visible }
      }
    },
    view: function (vnode) {
      return m(vnode.state.visible ? '.visible' : '.hidden', {
        onclick: vnode.state.toggleMe
      }, 'Test')
    }
  }

  // actual test
  var out = mq(module)
  out.should.have('.visible')
  out.click('.visible')
  out.should.have('.hidden')
  out.click('.hidden', null, true)
  out.should.have('.hidden')

As you can see, you can prevent autoredraw by providing a true as last argument to click method.

You can also manually trigger redraw:

var out = mq(module)
out.should.have('.visible')
out.redraw()

helpers

If you need to access the rendered root element you can simply access it with

out.rootNode

If you've rendered a component it might be handy to access the vnode directly. This can be with out.vnode:

var myComponent = {
  view: function (vnode) {
    vnode.state.baz = 'foz'
  }
}
var out = mq(myComponent)
expect(out.vnode.state.baz).toEqual('foz')

onremove handling

To trigger onremove-handlers of all initialised components, just call out.onremove()

mithril-query's People

Contributors

stephanhoyer avatar greenkeeperio-bot avatar jmooradi avatar magnetised avatar der-on avatar sl014066 avatar quafzi avatar barneycarroll avatar limdauto avatar fossamagna avatar alfredmachineuser avatar richardivan avatar samueltilly avatar gitter-badger avatar tombh avatar

Watchers

Noah Hüsser avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.