【问题标题】:Writing Unit Test Cases for Preact为 Preact 编写单元测试用例
【发布时间】:2018-04-04 19:33:47
【问题描述】:

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

【问题讨论】:

  • 什么错误给了你?现在我正在研究使用酶,因为第 3 版已经发布并且可以用于测试更多的框架,而不仅仅是 React。 FWIW,preact 的 github 中的这个问题有几个选项:github.com/developit/preact/issues/658

标签: jestjs enzyme preact


【解决方案1】:

使用 preact-render-spy 查看this template project,它不依赖于反应和酶。另外还配置了 TypeScript。

【讨论】:

    【解决方案2】:

    更新

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

    原答案

    This preact boilerplate project 有一个包含单元测试的设置。他们正在使用jest 运行测试。

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

    package.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) );
    

    home/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');
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多