【问题标题】:Prevent Jasmine Test expect() Resolving Before JS Finished Executing在 JS 完成执行之前阻止 Jasmine 测试 expect() 解析
【发布时间】:2019-03-29 10:31:47
【问题描述】:

我希望你能提供帮助。我对单元测试相当陌生。我有一个运行 PhantomJS 浏览器的 Karma + Jasmine 设置。这一切都很好。

我正在努力解决的是我在页面上有一个链接,当点击这个链接时,它会注入一些 HTML。我想测试一下是否注入了 HTML。

现在,我可以进行测试,但只是有时,从我可以判断我的 JS 运行速度是否足够快,HTML 会在 expect() 运行之前被注入。如果不是,则测试失败。

如何让我的 Jasmine 测试在 expect() 运行之前等待所有 JS 完成执行?

有问题的测试是it("link can be clicked to open a modal", function() {

modal.spec.js

const modalTemplate = require('./modal.hbs');

import 'regenerator-runtime/runtime';
import 'core-js/features/array/from';
import 'core-js/features/array/for-each';
import 'core-js/features/object/assign';
import 'core-js/features/promise';

import Modal from './modal';

describe("A modal", function() {

    beforeAll(function() {
        const data = {"modal": {"modalLink": {"class": "", "modalId": "modal_1", "text": "Open modal"}, "modalSettings": {"id": "", "modifierClass": "", "titleId": "", "titleText": "Modal Title", "closeButton": true, "mobileDraggable": true}}};
        const modal = modalTemplate(data);
        document.body.insertAdjacentHTML( 'beforeend', modal );
    });

    it("link exists on the page", function() {
        const modalLink = document.body.querySelector('[data-module="modal"]');
        expect(modalLink).not.toBeNull();
    });

    it("is initialised", function() {
        spyOn(Modal, 'init').and.callThrough();
        Modal.init();

        expect(Modal.init).toHaveBeenCalled();
    });

    it("link can be clicked to open a modal", function() {
        const modalLink = document.body.querySelector('[data-module="modal"]');
        modalLink.click();

        const modal = document.body.querySelector('.modal');
        expect(modal).not.toBeNull();
    });

    afterAll(function() {

        console.log(document.body);

        // TODO: Remove HTML

    });

});

编辑 - 更多信息

为了进一步详细说明这一点,我认为,放在 cmets 中的链接 Jasmine 2.0 how to wait real time before running an expectation 帮助我更好地理解了一点。所以我们所说的我们想要spyOn 函数并等待它被调用,然后启动一个回调,然后解决测试。

太棒了。

我的下一个问题是,如果您查看下面我的 ModalViewModel 类的结构,我需要能够 spyOn insertModal() 才能做到这一点,但唯一可以在 @ 中访问的函数987654331@。我该怎么做才能继续使用这种方法?

import feature from 'feature-js';
import { addClass, removeClass, hasClass } from '../../01-principles/utils/classModifiers';
import makeDraggableItem from '../../01-principles/utils/makeDraggableItem';
import '../../01-principles/utils/polyfil.nodeList.forEach'; // lt IE 12

const defaultOptions = {
    id: '',
    modifierClass: '',
    titleId: '',
    titleText: 'Modal Title',
    closeButton: true,
    mobileDraggable: true,
};

export default class ModalViewModel {
    constructor(module, settings = defaultOptions) {
        this.options = Object.assign({}, defaultOptions, settings);
        this.hookModalLink(module);

    }

    hookModalLink(module) {
        module.addEventListener('click', (e) => {
            e.preventDefault();


            this.populateModalOptions(e);
            this.createModal(this.options);
            this.insertModal();

            if (this.options.closeButton) {
                this.hookCloseButton();
            }

            if (this.options.mobileDraggable && feature.touch) {
                this.hookDraggableArea();
            }

            addClass(document.body, 'modal--active');

        }, this);
    }

    populateModalOptions(e) {
        this.options.id = e.target.getAttribute('data-modal');
        this.options.titleId = `${this.options.id}_title`;
    }

    createModal(options) {
        // Note: As of ARIA 1.1 it is no longer correct to use aria-hidden when aria-modal is used
        this.modalTemplate = `<section id="${options.id}" class="modal ${options.modifierClass}" role="dialog" aria-modal="true" aria-labelledby="${options.titleId}" draggable="true">
                                ${options.closeButton ? '<a href="#" class="modal__close icon--cross" aria-label="Close" ></a>' : ''}
                                ${options.mobileDraggable ? '<a href="#" class="modal__mobile-draggable" ></a>' : ''}
                                <div class="modal__content">
                                    <div class="row">
                                        <div class="columns small-12">
                                            <h2 class="modal__title" id="${options.titleId}">${options.titleText}</h2>
                                        </div>
                                    </div>
                                </div>
                            </section>`;

        this.modal = document.createElement('div');
        addClass(this.modal, 'modal__container');
        this.modal.innerHTML = this.modalTemplate;
    }

    insertModal() {
        document.body.appendChild(this.modal);
    }

    hookCloseButton() {
        this.closeButton = this.modal.querySelector('.modal__close');

        this.closeButton.addEventListener('click', (e) => {
            e.preventDefault();
            this.removeModal();
            removeClass(document.body, 'modal--active');
        });
    }

    hookDraggableArea() {
        this.draggableSettings = {
            canMoveLeft: false,
            canMoveRight: false,
            moveableElement: this.modal.firstChild,
        };

        makeDraggableItem(this.modal, this.draggableSettings, (touchDetail) => {
            this.handleTouch(touchDetail);
        }, this);
    }

    handleTouch(touchDetail) {
        this.touchDetail = touchDetail;
        const offset = this.touchDetail.moveableElement.offsetTop;

        if (this.touchDetail.type === 'tap') {
            if (hasClass(this.touchDetail.eventObject.target, 'modal__mobile-draggable')) {

                if (offset === this.touchDetail.originY) {
                    this.touchDetail.moveableElement.style.top = '0px';
                } else {
                    this.touchDetail.moveableElement.style.top = `${this.touchDetail.originY}px`;
                }

            } else if (offset > this.touchDetail.originY) {
                this.touchDetail.moveableElement.style.top = `${this.touchDetail.originY}px`;
            } else {
                this.touchDetail.eventObject.target.click();
            }
        } else if (this.touchDetail.type === 'flick' || (this.touchDetail.type === 'drag' && this.touchDetail.distY > 200)) {

            if (this.touchDetail.direction === 'up') {

                if (offset < this.touchDetail.originY) {
                    this.touchDetail.moveableElement.style.top = '0px';
                } else if (offset > this.touchDetail.originY) {
                    this.touchDetail.moveableElement.style.top = `${this.touchDetail.originY}px`;
                }

            } else if (this.touchDetail.direction === 'down') {

                if (offset < this.touchDetail.originY) {
                    this.touchDetail.moveableElement.style.top = `${this.touchDetail.originY}px`;
                } else if (offset > this.touchDetail.originY) {
                    this.touchDetail.moveableElement.style.top = '95%';
                }

            }
        } else {
            this.touchDetail.moveableElement.style.top = `${this.touchDetail.moveableElementStartY}px`;
        }
    }

    removeModal() {
        document.body.removeChild(this.modal);
    }

    static init() {
        const instances = document.querySelectorAll('[data-module="modal"]');

        instances.forEach((module) => {
            const settings = JSON.parse(module.getAttribute('data-modal-settings')) || {};
            new ModalViewModel(module, settings);
        });
    }
}

更新

通过后发现.click() 事件是异步的,这就是为什么我开始关注种族问题。文档和堆栈溢出问题深思熟虑,网络建议使用 createEvent()dispatchEvent(),因为 PhantomJs 不理解 new MouseEvent()

这是我现在正在尝试执行此操作的代码。

modal.spec.js

// All my imports and other stuff
// ...

function click(element){
    var event = document.createEvent('MouseEvent');
    event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(event);
}

describe("A modal", function() {

    // Some other tests
    // Some other tests

    it("link can be clicked to open a modal", function() {
        const modalLink = document.body.querySelector('[data-module="modal"]');
        click(modalLink);

        const modal = document.body.querySelector('.modal');
        expect(modal).not.toBeNull();
    });

    // After all code
    // ...

});

不幸的是,这产生了相同的结果。更近了 1 步,但还不够。

【问题讨论】:

  • 请查看此链接以获得更多帮助 - stackoverflow.com/questions/21176795/…
  • 嘿@demouser123,我不确定这是否有帮助,因为我没有进行 AJAX 调用,我只是创建一个 HTML 字符串并将其注入 DOM。
  • @CodyKnapp 我真的同意你的观点,这对我来说也没有什么意义,我要做的只是在我的afterAll 函数中console.log(document.body); 有时会注入 HTML 和有时它不会。我的假设是这是一个种族问题,但也许不是?
  • 经过一番研究(很抱歉删除了我的评论 - 我没有看到你的评论),我发现点击是异步的。这就是为什么您在断言和您添加的单击事件处理程序之间获得这种竞争条件的原因。那是我看到的唯一可能的东西。我正在环顾四周,看看是否有什么方便的东西可以等待点击的整个过程完成。
  • @CodyKnapp 啊,很高兴知道,谢谢你的帮助,希望你能找到一些东西,因为我很难过。

标签: javascript unit-testing jasmine phantomjs karma-jasmine


【解决方案1】:

经过一番研究,看起来您对 click 事件的使用触发了一个异步事件循环,本质上是说“嘿,设置这个东西被点击,然后触发所有处理程序”

您当前的代码看不到这一点,也没有真正的等待方式。我相信您应该能够使用此处的信息构建和发送鼠标单击事件。 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

我认为这应该允许您构建一个点击事件并将其分派到您的元素上。不同之处在于 dispatchEvent 是同步的 - 它应该阻止您的测试,直到点击处理程序完成。这应该允许您在没有失败或竞争条件的情况下进行断言。

【讨论】:

  • 太棒了,这是朝着正确方向迈出的一步,谢谢。我的下一个障碍是 PhantomJS 不支持 new MouseEvent(),这是使用 .dispatchEvent() 所必需的。
  • 如果您对使用 jquery 之类的东西不感兴趣,我会说这就是这种方法。如果您使用它,您可以使用 jquery 的 trigger 函数并将其交给回调来执行您的断言
  • 同意 jQuery 的 trigger 甚至可能会使这更容易,但如果可能的话,我真的很想避免将 jQuery 混入其中。
【解决方案2】:

我终于找到了解决办法。

这有两部分,第一部分来自@CodyKnapp。他对异步运行的 click() 函数的洞察有助于解决问题的第一部分。

这是这部分的代码。

modal.spec.js

// All my imports and other stuff
// ...

function click(element){
    var event = document.createEvent('MouseEvent');
    event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(event);
}

describe("A modal", function() {

    // Some other tests
    // Some other tests

    it("link can be clicked to open a modal", function() {
        const modalLink = document.body.querySelector('[data-module="modal"]');
        click(modalLink);

        const modal = document.body.querySelector('.modal');
        expect(modal).not.toBeNull();
    });

    // After all code
    // ...


});

这允许代码同步运行。

第二部分是我对如何编写 Jasmine 测试的理解不佳。在我最初的测试中,我在it("is initialised", function() { 内部运行Modal.init(),而实际上我想在beforeAll() 内部运行它。这解决了我的测试并不总是成功的问题。

这是我的最终代码:

modal.spec.js

const modalTemplate = require('./modal.hbs');

import '@babel/polyfill';

import Modal from './modal';

function click(element){
    var event = document.createEvent('MouseEvent');
    event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(event);
}

describe("A modal", function() {

    beforeAll(function() {
        const data = {"modal": {"modalLink": {"class": "", "modalId": "modal_1", "text": "Open modal"}, "modalSettings": {"id": "", "modifierClass": "", "titleId": "", "titleText": "Modal Title", "closeButton": true, "mobileDraggable": true}}};
        const modal = modalTemplate(data);
        document.body.insertAdjacentHTML( 'beforeend', modal );

        spyOn(Modal, 'init').and.callThrough();
        Modal.init();
    });

    it("link exists on the page", function() {
        const modalLink = document.body.querySelector('[data-module="modal"]');
        expect(modalLink).not.toBeNull();
    });

    it("is initialised", function() {
        expect(Modal.init).toHaveBeenCalled();
    });

    it("link can be clicked to open a modal", function() {
        const modalLink = document.body.querySelector('[data-module="modal"]');
        click(modalLink);

        const modal = document.body.querySelector('.modal');
        expect(modal).not.toBeNull();
    });

    afterAll(function() {

        console.log(document.body);

        // TODO: Remove HTML

    });

});

【讨论】:

  • 我很高兴看到你把这一切都解决了。然而,我认为监视和测试 init 可能没有必要。如果 init 没有提供其他可验证的行为,则可能需要重新评估它是否值得拥有。
  • 嘿@Co​​dyKnapp,这是一个很好的观点,我将考虑什么是最好的测试和我的一般测试策略。正如我之前所说,这是我第一次尝试,所以非常欢迎任何提示/提示!谢谢。
  • 我会说这真的取决于您的公共界面。我猜您正在使用测试中的 DOM 元素和行为......在这种情况下,我建议您测试的是与 DOM 的交互行为符合您的预期。只要行为正确,为了实现这一目标而必须发生的任何事情都与测试无关。
  • 我很高兴分享更多关于它的想法 - 特别是如果您有具体问题 - 请随时向我发送任何想法/问题!
  • @CodyKnapp 感谢您的帮助和建议,我已经重构了我的代码以更合乎逻辑的方式工作并测试必要的项目。我不会在这里发帖,因为它无关紧要,但你帮了大忙。
猜你喜欢
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2019-06-26
  • 2012-11-15
相关资源
最近更新 更多