404 错误,在 webcomponent 单元测试期间未找到 html

404 error, not finding html during webcomponent unit test

当我 运行 karma 测试导入 HTML 文件的 javascript 文件时,我希望 html 可用于测试。我不清楚我是否正在尝试一些不是业力准备的东西,或者我应该在开始测试之前以某种方式添加 HTML 文件。

简而言之,我应该怎么做才能对分成两个文件(js 和 html)的 webcomponent 进行单元测试?也许有用的评论是,如果我误解了有关业力的错误(例如,它无法加载由 javascript 异步导入的文件)

控制台错误:

# npm run test

> skyscanner-openwc-graphql@0.0.0 test C:\_d\WSs\rapidapi-vanilla-webcomponents\skyscanner-openwc-graphql
> karma start --coverage


START:
12 08 2019 15:29:40.982:WARN [filelist]: Pattern "C:/_d/WSs/rapidapi-vanilla-webcomponents/skyscanner-openwc-graphql/__snapshots__/**/*.md" does not match any file.
12 08 2019 15:29:41.005:INFO [karma-server]: Karma v4.2.0 server started at http://0.0.0.0:9876/
12 08 2019 15:29:41.007:INFO [launcher]: Launching browsers ChromeHeadlessNoSandbox with concurrency unlimited
12 08 2019 15:29:41.013:INFO [launcher]: Starting browser ChromeHeadless
12 08 2019 15:29:42.172:INFO [HeadlessChrome 76.0.3809 (Windows 10.0.0)]: Connected on socket fPyJTkm8LvWTrPBoAAAA with id 27628633
12 08 2019 15:29:47.926:WARN [web-server]: 404: /src/skyscanner-flight-search/skyscanner-flight-search.html
  skyscanner flight search
    × show div
HeadlessChrome 76.0.3809 (Windows 10.0.0) skyscanner flight search show div FAILED
        TypeError: Cannot read property 'querySelector' of null
            at Context.querySelector (test/skyscanner-flight-search.test.js:10:23)

Finished in 0.102 secs / 0.022 secs @ 15:29:48 GMT-0300 (GMT-03:00)

SUMMARY:
√ 0 tests completed
× 1 test failed

FAILED TESTS:
  skyscanner flight search
    × show div
      HeadlessChrome 76.0.3809 (Windows 10.0.0)
    TypeError: Cannot read property 'querySelector' of null
        at Context.querySelector (test/skyscanner-flight-search.test.js:10:23)

Web组件,javascript文件(skyscanner-flight-search.js):

(async() => {
    const res = await fetch(
        "../src/skyscanner-flight-search/skyscanner-flight-search.html"
    );
    const textTemplate = await res.text();

    const HTMLTemplate = new DOMParser()
        .parseFromString(textTemplate, "text/html")
        .querySelector("template");

    class skyscannerFlightSearch extends HTMLElement {
        constructor() {
            super();
        }

        connectedCallback() {
            this.attachShadow({ mode: "open" });
            this.shadowRoot.appendChild(HTMLTemplate.content.cloneNode(true));

            const inputSessionKey = this.shadowRoot.getElementById("inputSessionKey");
            //const url = "http://localhost:8080/getsessionkey";
            const url = "https://rapid-api-to-learn.herokuapp.com/getsessionkey";

            fetch(url)
                .then(function(body) {
                    return body.text();
                })
                .then(function(data) {
                    inputSessionKey.value = data;
                    console.log(data);
                });
        }
    }

    window.customElements.define(
        "skyscanner-flight-search",
        skyscannerFlightSearch
    );
})();

Web组件,html文件(skyscanner-flight-search.html)

<template id="skyscanner-flight-search-template"
  ><div id="firstdiv"><input id="inputSessionKey" /></div
></template>

依赖关系(只是相关的)

    "scripts": {
...
        "test": "karma start --coverage",
...

    },
    "dependencies": {
        "lit-html": "^1.0.0",
        "lit-element": "^2.0.1"
    },
    "devDependencies": {
        "es-dev-server": "^1.5.0",
        "@open-wc/eslint-config": "^1.0.0",
        "@open-wc/prettier-config": "^0.1.10",
        "husky": "^1.0.0",
        "lint-staged": "^8.0.0",
        "@open-wc/testing-karma": "^3.0.0",
        "webpack-merge": "^4.1.5",
        "@open-wc/testing-karma-bs": "^1.0.0",
        "@open-wc/testing": "^0.11.1",
        "@open-wc/demoing-storybook": "^0.3.0"
    },

karma.conf.js

const { createDefaultConfig } = require('@open-wc/testing-karma');
const merge = require('webpack-merge');

module.exports = config => {
    config.set(
        merge(createDefaultConfig(config), {
            files: [

                { pattern: config.grep ? config.grep : 'test/**/*-search.test.js', type: 'module' },
            ],

            esm: {
                nodeResolve: true,
            },
            // you can overwrite/extend the config further
        }),
    );
    return config;
};

感谢讨论https://github.com/open-wc/open-wc/issues/730我找到了解决方案:

我必须做两件事才能对分成两个文件的香草 Web 组件进行单元测试:

我的网络组件javascript

'
const htmlPath = new URL(
'./skyscanner-flight-search.html',
import.meta.url,
);
const res = await fetch(htmlPath);
...
'

我的单元测试

'
import { html, fixture, expect } from '@open-wc/testing';

import '../src/skyscanner-flight-search/skyscanner-flight-search.js';

describe('skyscanner flight search', () => {
it('show div', async() => {
const el = await fixture(html <skyscanner-flight-search></skyscanner-flight-search>);

    window.customElements.whenDefined('skyscanner-flight-search').then(() => {
        el.shadowRoot.querySelector('#firstdiv');
        expect(el).to.exist;
    })

});
});
'

可能我遗漏了一些关于 Karma 为单元测试 javascript 获取文本文件所花费的时间和步骤的基本概念。顺便说一句,上述方法解决了问题标题。

*** 根据讨论编辑 https://dev.to/bennypowers/lets-build-web-components-part-3-vanilla-components-4on3

import { html, fixture, expect } from '@open-wc/testing';

import '../src/skyscanner-flight-search/skyscanner-flight-search.js';

describe('skyscanner flight search', () => {
    it('show div', async() => {
        const el = await fixture(html `
      <skyscanner-flight-search></skyscanner-flight-search>
    `);
        await window.customElements.whenDefined('skyscanner-flight-search')
        expect(el.shadowRoot.querySelector('#firstdiv')).to.exist;

    });

    it('show input for session key', async() => {
        const el = await fixture(html `
      <skyscanner-flight-search></skyscanner-flight-search>
    `);
        await window.customElements.whenDefined('skyscanner-flight-search')
        expect(el.shadowRoot.querySelector('#inputSessionKey')).to.exist;
    });
});