I'm trying to test a ES6 function which updates the dom element whenever it is being executed. Currently I'm getting empty nodelist since the HTML page is not loaded. What is approach to test this purely with JEST?
jest.dontMock('../scripts/taskModel');
import Request from '../__mocks__/request';
import Task from '../scripts/taskModel';
describe('taskModel', () => {
it('Should initialize with no friends items', function() {
expect(document.querySelectorAll('.panel-block').length).toBe(1); // THIS IS ALWAYS RETURNS EMPTY NODELIST
var task = new Task();
task.index();
expect(document.querySelectorAll('.panel-block').length).toBeGreaterThanOrEqual(6); // THIS IS ALWAYS RETURNS EMPTY NODELIST
});
});
Jest ships with jsdom which simulates a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser! So we can very easy to simulates a DOM environment when use Jest, get start install Jest and write test case!
An exploration into the HTMLElement type These documents are static, they do not change. The Document Object Model (DOM) is a programming interface implemented by browsers in order to make static websites functional. The DOM API can be used to change the document structure, style, and content.
Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.
A reminder that if the dataset property is being used by the JS under test, then because jsdom doesn't (yet) support the dataset attribute, there is a handy polyfill, which will also insert DOM content for you - https://www.npmjs.com/package/jsdom-mount
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With