首頁  >  文章  >  web前端  >  如何建構測試環境? Angular測試工具集介紹

如何建構測試環境? Angular測試工具集介紹

青灯夜游
青灯夜游轉載
2020-08-22 11:16:322461瀏覽

如何建構測試環境? Angular測試工具集介紹

本文將探討如何建構測試環境、以及Angular測試工具集。

測試環境

絕大部分都是利用Angular Cli來創建項目,因此,預設已經整合我們所需要的npm套件與腳本;當然,如果你是使用自建或官網quickstart 的話,需要自行安裝;但所有核心數據都是一樣的。 【相關教學推薦:angular教學

Angular單元測試我們可以將其分成兩類:獨立單獨測試與Angular測試工具集。

Pipe與Service適為獨立單獨測試,因為它們只需要 new 實例類別即可;同樣是無法與Angular元件進行任何互動。

與之相反就是Angular測試工具集。

測試框架介紹

Jasmine

Jasmine測試框架提供了編寫測試腳本的工具集,而且非常優秀的語義化,讓測試程式碼看起來像是在讀一段話。

Karma

有測試腳本,也需要Karma來幫忙管理這些腳本,以便在瀏覽器中運作。

Npm 套件

如果你非要折騰,那麼最簡單的辦法就是透過Angular Cli建立一個新項目,然後將以下Npm包複製到您折騰的項目中。

    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0"

那麼,我們重要還是看設定腳本部分。

設定腳本

我們核心是需要讓karma 運行器運行起來,而對於Jasmine,是在我們編寫測試腳本時才會使用到,因此,暫時無須過度關心。

我們需要在根目錄建立 karma.conf.js 文件,這相當於一些約定。文件是為了告知karma需要啟用哪些外掛程式、載入哪些測試腳本、需要哪些測試瀏覽器環境、測試報告通知方式、日誌等等。

karma.conf.js

以下是Angular Cli預設提供的karma 設定檔:

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function(config) {
    config.set({
        // 基础路径(适用file、exclude属性)
        basePath: '',
        // 测试框架,@angular/cli 指Angular测试工具集
        frameworks: ['jasmine', '@angular/cli'],
        // 加载插件清单
        plugins: [
            require('karma-jasmine'),
            require('karma-chrome-launcher'),
            require('karma-jasmine-html-reporter'),
            require('karma-coverage-istanbul-reporter'),
            require('@angular/cli/plugins/karma')
        ],
        client: {
            // 当测试运行完成后是否清除上文
            clearContext: false // leave Jasmine Spec Runner output visible in browser
        },
        // 哪些文件需要被浏览器加载,后面会专门介绍  `test.ts`
        files: [
            { pattern: './src/test.ts', watched: false }
        ],
        // 允许文件到达浏览器之前进行一些预处理操作
        // 非常丰富的预处理器:https://www.npmjs.com/browse/keyword/karma-preprocessor
        preprocessors: {
            './src/test.ts': ['@angular/cli']
        },
        // 指定请求文件MIME类型
        mime: {
            'text/x-typescript': ['ts', 'tsx']
        },
        // 插件【karma-coverage-istanbul-reporter】的配置项
        coverageIstanbulReporter: {
            // 覆盖率报告方式
            reports: ['html', 'lcovonly'],
            fixWebpackSourcePaths: true
        },
        // 指定angular cli环境
        angularCli: {
            environment: 'dev'
        },
        // 测试结果报告方式
        reporters: config.angularCli && config.angularCli.codeCoverage ?
            ['progress', 'coverage-istanbul'] :
            ['progress', 'kjhtml'],
        port: 9876,
        colors: true,
        // 日志等级
        logLevel: config.LOG_INFO,
        // 是否监听测试文件
        autoWatch: true,
        // 测试浏览器列表
        browsers: ['Chrome'],
        // 持续集成模式,true:表示浏览器执行测试后退出
        singleRun: false
    });
};

以上設定基本上可以滿足我們的需求;一般需要變動的,我想是測試瀏覽器清單了,因為karma支援所有市面上的瀏覽器。另外,當你使用Travis CI 持續整合時,啟動一個禁用沙箱環境Chrome瀏覽器會讓我們少了很多事:

        customLaunchers: {
            Chrome_travis_ci: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        }

有關karma config文件的所有信息,請參與官網文檔

test.ts

在寫karma.conf.js 時,我們配置過瀏覽器載入的檔案指向的是 ./src/test.ts 檔案。作用是為了引導 karma 啟動,程式碼也簡單許多:

// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function () {};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
// 所有.spec.ts文件
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();

一切就緒後,我們可以嘗試啟動 karma 試一下,即使沒有任何測試程式碼,也是可以運行的。

如果是Angular Cli那麼 ng test折騰的用node "./node_modules/karma-cli/bin/karma" start

最後,開啟瀏覽器:http://localhost :9876,可以查看測試報告。

簡單範例

既然環境搭好,那麼我們來寫個簡單範例試試看。

建立 ./src/demo.spec.ts 檔案。 .spec.ts為後綴這是一個約定,遵守它。

describe('demo test', () => {
    it('should be true', () => {
        expect(true).toBe(true);
    })
});

運行ng test 後,我們可以在控制台看到:

Chrome 58.0.3029 (Windows 10 0.0.0): Executed 1 of 1 SUCCESS (0.031 secs / 0.002 secs)

或瀏覽器:

1 spec, 0 failures
demo test
  true is true

不管怎麼樣,畢竟我們已經進入Angular單元測試的世界了。

Angular測試工具集

普通類別諸如Pipe或Service,只需要透過簡單的 new 建立實例。而對於指令、元件而言,需要一定的環境。這是因為Angular的模組概念,要想元件能運行,首先得有一個 @NgModule 定義。

工具集的資訊量並不很多,你很容易可以掌握它。下面我簡單說明幾個最常用的:

TestBed

#TestBed 是Angular測試工具集提供的用來建構一個 @NgModule 測試環境模組。當然有了模組,還需要利用 TestBed.createComponent 建立一個用於測試目標元件的測試元件。

非同步

Angular到處都是非同步,而非同步測試可以利用工具集中asyncfakeAsync# 編寫優雅測試代碼看著是同步。

工具集還有更多,這一切我們將在[Angular單元測試-元件與指令單元測試]()逐一說明。

happy coding!

#

以上是如何建構測試環境? Angular測試工具集介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除