微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 CDN 样式表链接导入 Cypress 组件测试运行器

如何解决如何将 CDN 样式表链接导入 Cypress 组件测试运行器

我有一个 vue-cli 项目。我已经使用官方文档成功设置了 cypress 组件测试运行程序:https://docs.cypress.io/guides/component-testing/introduction。现在,我在使用通过 CDN 链接(即 fontawesome 和 mdi 图标)在我的应用程序中提供的图标字体时遇到了问题,这些图标字体包含在我的 index.html 中。这些链接之一,例如:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@latest/css/materialdesignicons.min.css" />

由于组件测试运行器没有加载 index.html,图标丢失,部分功能无法测试。而且我还没有找到可以包含这些链接的地方(在每个 <component>.vue 文件中导入它们不是解决方案)。

有没有人有解决这个问题的方法

注意:我不想安装这些框架的 npm 包。我需要使用 CDN 交付的版本。

解决方法

Cypress 封装了 vue-test-utils mount() 函数,它有一个 attachTo 选项,因此您可以通过这种方式将 CDN 链接添加到测试中

HelloWorld.spec.ts

import { mount } from '@cypress/vue'
import HelloWorld from './HelloWorld.vue'

describe('HelloWorld',() => {
  it('renders a message',() => {
    const msg = 'Hello Cypress Component Testing!'

    // This elem is to attach the component to document 
    const elem = document.createElement('div')
    if (document.body) {
      document.body.appendChild(elem)
    }

    // Attach the CDN link to document
    const linkElem = document.createElement('link');
    linkElem.setAttribute('rel','stylesheet');
    linkElem.setAttribute('href','https://cdn.jsdelivr.net/npm/@mdi/font@latest/css/materialdesignicons.min.css');
    if (document.head) {
      document.head.appendChild(linkElem)
    }

    mount(HelloWorld,{
      propsData: {
        msg
      },attachTo: elem
    })

    cy.get('i').should('be.visible');             // fails if the CDN link is omitted

  })
})

我不确定这些图标对测试逻辑有何影响,但您可以验证它们是由 cy.get('i').should('be.visible') 加载的。

如果未加载(注释掉上面的 linkElem)测试失败

这个元素不可见
因为它的有效宽度和高度为:0 x 0 像素。

带图标的HelloWorld.vue模板

<template>
  <div class="hello">
    <h1><i class="mdi mdi-account"></i> {{ msg }}</h1>

顺便说一句,我无法让文档中的示例工作,我不得不使用 vue-cypress-template

参考 Getting Started with Cypress Component Testing (Vue 2/3) - Apr 06 2021 • Lachlan Miller

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?