简体   繁体   中英

how to test the View using class methods(that created HTML) with TypeScript, JSDOM, Mocha, Chai?

I can't get JSDOM "document" in class View when i call it. What i need to do?

I installed all @types/ dependencies and JSDOM work well in situation then i call it directly from tests, and didn't work when i call View.ts

//view.ts

interface View {
  _element_id?: string,
  _elem?: any,
};

class View {
  constructor(param: View) {
    this._element_id = param._element_id;
    this._elem = document.getElementById(param._element_id);
}
a = document.getElementById(this._element_id).textContent
}

export { View };

Then i created a test file and it looks like

//test.ts

import { View } from 'view';
import { assert } from 'chai';
import { JSDOM, FromFileOptions, DOMWindow } from 'jsdom';

const dom = new JSDOM(`<!DOCTYPE html><html><body><div id="slider">Hello!</div></body></html>`);
let document = dom.window.document;

let view = new View({
    _element_id: "slider"} as View)

describe('Test View',
    () => {
it('Simple JSDOM', () => {
    let a = document.getElementById("slider").textContent;
    assert.equal(a, "Hello!")};

First test is ok, But i need to run next test, that now doesn't work

it('Call JSDOM from class View', () => {
    let a = view.a;
    assert.equal(a, "Hello!")}
};

the error is

this._elem = document.getElementById(param._element_id);
               ^
ReferenceError: document is not defined

So, it is how i got "document" in View class

//test.ts

import { View } from 'view';
import { expect, assert } from 'chai';
import * as mocha from 'mocha';

import { JSDOM, FromFileOptions, DOMWindow } from 'jsdom';

describe('Test View',
    () => {

        describe('Trial testing',
            () => {

                let view: any;

                beforeEach(function () {

                    return JSDOM.fromFile('./index.html').then((dom) => {

                            const { window } = dom;

                            view = new View({
                                _element_id: "slider",
                            } as View);
                        });

                });

                it('Get element with id', () => {

                    assert.equal(view.a, "Hello!")};

                });

            });

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM