LANGUAGE/!$%!% ERROR NOTE
[Mocha] ReferenceError: document is not defined
forgiveall
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을 이용할 수 있다.
Install
mocha-jsdom
npm i -D mocha-jsdom
Set
jsdom()
to document in the global scopeconst jsdom = require('mocha-jsdom'); global.document = jsdom({url: "http://localhost"});
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); }); });
Run test
mocha
4. Reference - 참조
- 'ReferenceError: document is not defined' error: https://stackoverflow.com/questions/51661741/referenceerror-document-is-not-defined-error
- mocha-jsdom - Test frontend libraries in the console using Node.js, mocha and jsdom.: https://www.npmjs.com/package/mocha-jsdom
- How to mock window/document with mocha/chai: https://stackoverflow.com/questions/36500723/how-to-mock-window-document-with-mocha-chai
- Mess with globals: https://github.com/mochajs/mocha/wiki/Mess-with-globals
- Using Chai to test value of HTML element: https://stackoverflow.com/questions/48331488/using-chai-to-test-value-of-html-element
- Uncaught TypeError: Cannot read property of null: https://idiallo.com/javascript/uncaught-typeerror-cannot-read-property-of-null