How to test JavaScript with DOM elements using jasmine?

只谈情不闲聊 提交于 2019-12-04 15:04:45

There HAS to be an environment where your js will execute.

  • Browser
  • Node

You can run your test in Browser using Karma(or you can find similar test runners). Karma executes the HTML/JS/Jasmine-Test-JS in a real browser like Chrome/IE/Firefox/Safari OR a headless browser like PhantomJS. You can also take advantage of jquery selectors here.

You can run your test in Node using JSDOM. Here a virtual DOM is created in-memory. You can use Cheerio to get a jquery like behaviour if you want to run selectors.

import {expect} from 'chai';
import jsdom from 'jsdom';
import fs from 'fs';

describe('index.html', ()=>{
  it('should have h1 that says Users', (done)=>{
    const index = fs.readFileSync('./src/index.html', "utf-8");
    jsdom.env(index, function(err, window){
      if(err){
        console.log(err);
      }
      else{
        const h1 = window.document.getElementsByTagName('h1')[0];
        expect(h1.innerHTML).to.equal("Users");
        done();
        window.close();
      }
    })
  })
})

To run test in Node, you will have to bring in the html content in a variable and initialize jsdom. Refer the example to see how a window object gets into picture by jsdom.

I had the same problem with document being 'undefined' plus problem with using ES6 (SyntaxError: Unexpected token import).

I used jasmine with babel and jsdom.

Jasmine can run test in Node or/and browser. I guess using Node version is more universal.

My solution:

jasmine.json

{
    "spec_dir": "spec",
    "spec_files": [
        "**/*[sS]pec.js"
    ],
    "helpers": [
        "../node_modules/babel-register/lib/node.js",   // load babel first to use ES6 'import' and other features
        "helpers/**/*.js"

    ],
    "stopSpecOnExpectationFailure": false,
    "random": true
}

testHelper.js

import jsdom from 'jsdom';
import fs from 'fs';

const index = fs.readFileSync('./static/index.html', 'utf-8');
const { JSDOM } = jsdom;

const { document } = (new JSDOM(index)).window;
global.document = document;

With above setup you can use 'document' in your tests.

PS: Above is not full babel setup. See babel documentation or other posts for that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!