【问题标题】:how to test the View using class methods(that created HTML) with TypeScript, JSDOM, Mocha, Chai?如何使用带有 TypeScript、JSDOM、Mocha、Chai 的类方法(创建 HTML)测试视图?
【发布时间】:2019-11-08 07:54:40
【问题描述】:

当我调用它时,我无法在类 View 中获取 JSDOM“文档”。我需要做什么?

我安装了所有 @types/ 依赖项,并且 JSDOM 在这种情况下运行良好,然后我直接从测试中调用它,当我调用 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 };

然后我创建了一个测试文件,它看起来像

//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!")};

第一次测试没问题!但是我需要运行下一个测试,现在不起作用

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

错误是

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

【问题讨论】:

    标签: javascript typescript mocha.js chai jsdom


    【解决方案1】:

    所以,这就是我在 View 类中获得“文档”的方式

    //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!")};
    
                    });
    
                });
    
        });
    

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多