angelodiego
angelodiego

Reputation: 245

Dom testing Mocha + karma

I'm trying some javascript tdd but I cannot figure out how to do dom testing with mocha and karma With mocha only it's pretty easy: I create an hmtl file

<!doctype html>
<html>
    <head>
        <title>Simple mocha test</title>
        <link rel="stylesheet" href="node_modules/mocha/mocha.css">
    </head>
    <body>
        <h1>Login</h1>
        <form>
          <input type="email" name="email" required>
          <button id="btn-login">Login</button>
        </form>
        <div id="mocha"></div>
        <script src="node_modules/mocha/mocha.js"></script>
        <script src="node_modules/chai/chai.js"></script>
        <script>
            mocha.ui('bdd'); 
            mocha.reporter('html'); 
            var expect = chai.expect; 
        </script>
        <script src="./test.js"></script>
        <script>
            mocha.run(); 
        </script>
    </body>
</html>

a js file

describe('Tests DOM  - login form', function() {
      var formElem = document.forms[0];
      var signupButton = document.getElementById('btn-login');

      it('has a form', function() {
        debugger;
        expect(formElem).to.not.equal(null);
      });

      it('input field is of type email', function() {
        expect(formElem.email.getAttribute('type')).to.equal('email');
      });

      it('login button has the right text', function() {
        expect(signupButton.innerHTML).to.equal('Login');
      });
    });

and run mocha

when I use karma to run my tests it does load the javascript but it executes it in a context where the html is not loaded, is there a way to tell karma to load the hmtl or modify the mocha script to do directly load the hmtl?

Upvotes: 2

Views: 1279

Answers (1)

Cheng-Han Kuo
Cheng-Han Kuo

Reputation: 1

please try karma-html2js-preprocessor

testing code

beforeEach ->

# inject html
if __html__?

    html = __html__['test/design/lib/jquery.loading.html']
    newDoc = document.open('text/html', 'replace')
    newDoc.write html
    newDoc.close()

karma config

   .....
   preprocessors: {
        'test/design/**/*.html': ['html2js']
   },
   ....
   plugins: [
        .....
        'karma-html2js-preprocessor',
    ]

Upvotes: 0

Related Questions