Defining mocha specs on the fly in the browser

时间:2016-02-12 19:28:46

标签: javascript mocha

I need to be able to execute mocha tests in the browser. Not using a cli tool to run tests in a browser via the terminal. Literally, everything in the browser. The goal is to run specs after the user clicks on a button.

I've got mocha setup correctly in the browser, but there's some caching behavior that's confusing me.

https://plnkr.co/edit/nuZZyD5EsMtpgP66HtW5?p=preview

The HTML :

<div id="mocha"></div>
<button id="test">run test</button>

The JS :

(function(init, $, runner) {
    init();
    $('#test').addEventListener('click', runner)
})(
    function init() {
        mocha.setup('bdd');
    },
    function $(sel) {
        return document.querySelector(sel);
    },
    function specRunner(e) {
        describe('test at ' + new Date().getTime(), function() {
            it('should add 1 + 1', function() {
                chai.assert(1 + 1 === 2, 'added 1 + 1');
            });
        });
        mocha.run();
    }
)

Other testing tools I've worked with (qunit, jasmine, karma, protractor) all encourge (force?) the user to have all their specs defined before the runner is started. This is the opposite of what I'm trying to achieve: define the specs programatically, not at run time.

In the plnkr, it seems like mocha is caching previous specs and then running all of them on every click. How can I get around this behavior?

1 个答案:

答案 0 :(得分:0)

I think this wors as you expect it:

    {
  "rules": {
    "networks": {
      "$networkid": {
//Give read and write access to the owner of the network 
        ".read": "auth != null && "root.child('networks').child($networkid).child('owner').val() == auth.uid",
        ".write": "auth != null && "root.child('networks').child($networkid).child('owner').val() == auth.uid",
        "pending_members": {
           "$uid": {
              //Give members write access to their own node inside pending_members
              ".write": "auth != null && auth.uid == $uid",
              //Use validate to check if the value is a bool or emty(removal)
              ".validate": newData.isBoolean() || !newData.exists()
      }
    }
  }
}

The problem was that you define the test every time you click the button, but you only need to define it once, and only run in the runner.

Hope this helps you