代码之家  ›  专栏  ›  技术社区  ›  Ekaterina M

如何使用Jest和测试库在JavaScript中进行单元测试?

  •  0
  • Ekaterina M  · 技术社区  · 1 年前

    我使用Jest和dom测试库,不使用REACT。

    我还在我的项目中使用webpack。我一直在解决同样的问题:

    expect(element).toBeInTheDocument()
    element could not be found in the document
    

    如何测试文档中是否有按钮?如果我使用没有脚本的静态HTML,我如何正确测试项目的模块?我应该手动添加脚本吗?我是第一次做,请帮帮我

    我的测试文件:

    import { getByRole } from '@testing-library/dom';
    import '@testing-library/jest-dom';
    import '@testing-library/jest-dom/extend-expect';
    
    function getExampleDOM() {
      const div = document.createElement('div');
      div.innerHTML = `
          <div class="screen">
            <h1 class="game__title">GAME 2048</h1>
            <button type="button" class="btn btn-start">Start</button>
          </div>
          <div class="screen">
            <h2 class="game__title">Choose board size</h2>
            <ul class="size-list">
              <li>
                <button type="button" class="btn btn-size" data-size="3">3 x 3</button>
              </li>
              <li>
                <button type="button" class="btn btn-size" data-size="4">4 x 4 (classic)</button>
              </li>
              <li>
                <button type="button" class="btn btn-size" data-size="5">5 x 5</button>
              </li>
            </ul>
          </div>
          <div class="game__wrapper">
            <h2 class="game__score-title">Your score:<span class="game__score">0</span></h2>
            <div class="game-board"></div>
          </div>
      `;
      return div;
    }
    
    describe('startGame', () => {
      test('renders all necessary elements', () => {
        const container = getExampleDOM();
        const startBtn = getByRole(container, 'button', { name: /start/i });
        expect(startBtn).toBeInTheDocument();
      });
    });
    
    

    我的包.json:

    {
      "name": "2048",
      "version": "1.0.0",
      "repository": {
        "url": "https://github.com/EkaterinaMuz/GAME2048.git"
      },
      "description": "",
      "scripts": {
        "test": "jest --w",
        "build": "webpack --mode development",
        "start": "webpack-dev-server --mode development --open",
        "predeploy": "npm run build",
        "deploy": "gh-pages -d dist"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "@babel/eslint-parser": "^7.21.8",
        "@babel/polyfill": "^7.12.1",
        "@babel/preset-env": "^7.21.5",
        "@testing-library/user-event": "^14.4.3",
        "babel-loader": "^9.1.2",
        "clean-webpack-plugin": "^4.0.0",
        "css-loader": "^6.7.4",
        "eslint": "^8.2.0",
        "eslint-config-airbnb-base": "^15.0.0",
        "eslint-config-prettier": "^8.8.0",
        "eslint-plugin-import": "^2.27.5",
        "eslint-plugin-jest-dom": "^4.0.3",
        "eslint-plugin-prettier": "^4.2.1",
        "eslint-plugin-testing-library": "^5.11.0",
        "eslint-webpack-plugin": "^4.0.1",
        "file-loader": "^6.2.0",
        "gh-pages": "^5.0.0",
        "html-webpack-plugin": "^5.5.1",
        "jest": "^29.5.0",
        "jest-webpack": "^0.5.1",
        "style-loader": "^3.3.3",
        "webpack": "^5.83.1",
        "webpack-cli": "^5.1.1",
        "webpack-dev-server": "^4.15.0"
      },
      "dependencies": {
        "@testing-library/jest-dom": "^5.16.5",
        "hammerjs": "^2.0.8",
        "jest-environment-jsdom": "^29.5.0"
      }
    }
    
    

    我还添加了Jest配置

    const config = {
      testEnvironment: 'jsdom',
      testEnvironmentOptions: {
        html: '<html lang="zh-cmn-Hant"></html>',
        url: 'https://jestjs.io/',
        userAgent: 'Agent/007',
      },
    };
    
    module.exports = config;
    
    

    我在项目中也有webpack:

    const path = require('path');
    const HTMLWebpackPlugin = require('html-webpack-plugin');
    const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    // const ESLintPlugin = require('eslint-webpack-plugin');
    
    module.exports = {
      mode: 'development',
      context: path.resolve(__dirname, 'src'),
      entry: ['@babel/polyfill', './scripts/index.js'],
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        assetModuleFilename: 'assets/[name][ext][query]',
      },
      devServer: {
        port: 3000,
      },
      plugins: [
        new HTMLWebpackPlugin({
          template: './index.html',
        }),
        new CleanWebpackPlugin(),
        // new ESLintPlugin({
        //   fix: true,
        // }),
      ],
      module: {
        rules: [
          {
            test: /\.css$/,
            use: ['style-loader', 'css-loader'],
          },
          // {
          //   test: /\.(png|jpg)$/,
          //   type: 'asset/resource',
          // },
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
              },
            },
          },
        ],
      },
    };
    
    

    ////////////////////////////////////

    0 回复  |  直到 1 年前