【问题标题】:How do I write tests using jQuery in ts-jest when using ES imports?使用 ES 导入时如何在 ts-jest 中使用 jQuery 编写测试?
【发布时间】:2019-11-22 01:24:03
【问题描述】:

我正在尝试使用 TypeScript、Jest 和 jQuery 编写单元测试。我已经走了很远,但是当我运行测试时,我得到“jQuery 需要一个带有文档的窗口”

显然,问题在于import * as $ from "jquery" (see this question) 也会初始化 jQuery,但当时没有窗口。我需要的是 jQuery 模块的“惰性”版本,类似于 $(document).ready(...) 通常会使用的,但对于 $ 符号本身。

背景:我将 jQuery 安装为 npm install @types/jquery。我正在使用jsdom 创建一个假窗口。我正在使用ts-jest 将TS 文件转换为jest 的JavaScript。使用npx jest --watch 或npm t 运行测试。

我想避免在Jest setupFile 中使用global.$,因为许多测试不需要开销。

【问题讨论】:

    标签: jquery jsdom ts-jest


    【解决方案1】:

    我有一个解决方案,但您不能在被测代码中使用 $,因此它仅适用于您编写/可以更改的代码。

    不要直接使用$,而是将其包装在提供程序中:

    export class JQueryProvider {
        constructor(public jq: any) {
            // empty
        }
    
        get(selector: string): JQuery {
            return this.jq(selector)
        }
    }
    

    这样,我们可以隐藏$ 的来源细节。即使输入 jq 的类型为 any,get() 方法也会将结果转换为正确的类型。

    此代码应进入共享实用程序模块。

    测试应该包含一个带有此设置代码的模块:

    import { JQueryProvider } from "./utils"
    import { JSDOM } from "jsdom";
    
    export type WithJQueryFunction = (jq: JQueryProvider) => void;
    
    export function withJQuery(fn: WithJQueryFunction): void {
        // Create window before loading jquery
        const window = new JSDOM().window 
    
        // Create jQuery instance
        const $ = require('jquery')(window);
    
        // Create provider to avoid the global variable $
        const jq = new JQueryProvider($)
    
        fn(jq)
    }
    

    请注意,我使用的是require() 而不是import,因为我不确定如何达到相同的效果。

    测试现在看起来像这样:

    withJQuery((jq) => {
        describe('jQuery tests', () => {
            it('empty div', () => {
                const parent = jq.get('<div>')
                expect(parent[0]).toMatchSnapshot()
            })      
    
            it('empty div with class', () => {
                const parent = jq.get('<div>').addClass('foo')
                expect(parent[0]).toMatchSnapshot()
            })      
        })
    })
    

    生产代码示例:

    export class DivAppender implements Appender {
        constructor(public jq: JQueryProvider, public parent: JQuery, public dateFormat = TIME_FORMAT) {
            // empty
        }
    
        append(event: LogEvent): void {
            const element = this.jq.get('<div>').addClass('event')
            ...
    
    const appender = new DivAppender(new JQueryProvider($), $('body'))
    

    【讨论】:

      猜你喜欢
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2018-07-25
      • 2018-08-12
      • 2018-07-26
      • 1970-01-01
      • 2018-09-17
      相关资源
      最近更新 更多