LANGUAGE/!$%!% ERROR NOTE 2020. 3. 22. 12:38

NodeJS - Mocha

1. Error - 오류

'ReferenceError: document is not defined' 
Uncaught TypeError: Cannot read property 'value' of null

2. Problem - 문제

NodeJS 에서는 기본적으로 Browser에서 사용되는 DOM에 관한 객체들이 존재하지 않는다.

3. Solved - 해결

uses document in the global scope before you declare the document.

jsdom을 이용하여 DOM을 이용할 수 있다.

  1. Install mocha-jsdom

     npm i -D mocha-jsdom
  2. Set jsdom() to document in the global scope

     const jsdom = require('mocha-jsdom');
     global.document = jsdom({url: "http://localhost"});
  3. Sample Test

    • {ROOT_OF_PROJECT}/test/sample-test.spec.js

        var assert = require('assert');
        var jsdom = require('mocha-jsdom');
        global.document = jsdom({url: "http://localhost"});
      
        describe('Sample Test', function() {      
          it('div element should exists when use createElement('div')', function() {
              var div = document.createElement('div');
            assert.equal(true, div != null);
          });
        });
  4. Run test

     mocha

4. Reference - 참조