3

我对 Preact 很陌生,我必须为 Preact 中的应用程序编写单元测试用例。我可以发现 jest 和酵素可以用于相同的用途,但我每次都会遇到错误。谁能推荐一些关于如何在 Preact 上编写单元测试用例的博客或教程?

4

2 回答 2

2

更新

现在可以使用preact-enzyme-adapter了,这使得使用Enzyme运行 preact 测试成为可能。我还没有测试过它,但我建议尝试一下,因为 Enzyme 有一个非常好的工具带并且已经被广泛使用。

原始答案

这个 preact 样板项目有一个包含单元测试的设置。他们jest用来运行测试。

据我了解,以下是启动和运行的相关部分。

包.json

  "jest": {
    "setupFiles": [
      "./test/setup.js"
    ],
    "testURL": "http://localhost:8080",
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less)$": "identity-obj-proxy",
      "^react$": "preact-compat",
      "^react-dom$": "preact-compat"
    },
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}"
    ]
  },

测试/setup.js:

import 'regenerator-runtime/runtime';
import chai from 'chai';
import assertJsx, { options } from 'preact-jsx-chai';

// when checking VDOM assertions, don't compare functions, just nodes and attributes:
options.functions = false;

// activate the JSX assertion extension:
chai.use(assertJsx);

global.sleep = ms => new Promise( resolve => setTimeout(resolve, ms) );

主页/index.test.js

import { h } from 'preact';
import { expect } from 'chai';

import Home from '../../../src/components/home';

describe('components/home', () => {
    it('should show the home text', () => {
        const home = <Home/>;
        expect(home).to.contain(<h1>Home</h1>);
        expect(home).to.contain('Home component');
    });
});
于 2017-10-26T14:12:11.010 回答
1

看看这个带有 preact-render-spy 的模板项目,它不依赖于反应和酶。由于还配置了 TypeScript。

于 2019-05-11T03:30:07.970 回答