Home  >  Article  >  Web Front-end  >  How to set up a test environment? Introduction to Angular testing toolset

How to set up a test environment? Introduction to Angular testing toolset

青灯夜游
青灯夜游forward
2020-08-22 11:16:322512browse

How to set up a test environment? Introduction to Angular testing toolset

This article will discuss how to build a test environment and the Angular testing tool set.

Test environment

Most of the projects are created using Angular Cli. Therefore, the npm packages we need have been integrated by default. Script; of course, if you use self-built or official website quickstart, you need to install it yourself; but all the core data are the same. [Related tutorial recommendations: angular tutorial]

We can divide Angular unit testing into two categories: independent individual testing and Angular testing toolset.

Pipe and Service are suitable for independent testing, because they only require new instance classes; they are also unable to interact with Angular components in any way.

The opposite is the Angular testing toolset.

Testing framework introduction

Jasmine

Jasmine testing framework provides tools for writing test scripts Set, and very good semantics, making the test code look like reading a paragraph.

Karma

There are test scripts, and Karma is needed to help manage these scripts so that they can be run in the browser.

Npm package

If you have to mess around, the easiest way is to create a new project through Angular Cli, and then add the following Copy the Npm package to the project you are working on.

    "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"

Then, the most important thing for us is to look at the configuration script part.

Configuration script

Our core is to let the karma runner run, and for Jasmine, it will be used when we write the test script, so for the time being No need to be overly concerned.

We need to create the karma.conf.js file in the root directory, which is equivalent to some conventions. The purpose of the file is to inform karma which plug-ins need to be enabled, which test scripts to load, which test browser environments are required, test report notification methods, logs, etc.

karma.conf.js

The following is the karma configuration file provided by Angular Cli by default:

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

The above configuration can basically meet our needs ; Generally, what needs to be changed is the test browser list, because karma supports all browsers on the market. In addition, when you use Travis CI continuous integration, starting a disable sandbox environment Chrome browser will save us a lot of things:

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

For all information about karma config files, please participate inOfficial website documentation .

test.ts

When writing karma.conf.js, we configured the file loaded by the browser to point to ./src/test.ts file. The function is to guide karma to start, and the code is much simpler:

// 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();

After everything is ready, we can try to start karma. It can run even without any test code.

If it is Angular Cli then ng test. Tossing withnode "./node_modules/karma-cli/bin/karma" start

Finally, open the browser: http://localhost :9876, you can view the test report.

Simple example

Now that the environment is set up, let’s write a simple example to try.

Create ./src/demo.spec.ts file. The suffix .spec.ts is a convention, follow it.

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

After running ng test, we can see in the console:

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

or browser:

1 spec, 0 failures
demo test
  true is true

No matter what , after all, we have entered the world of Angular unit testing.

Angular Testing Toolset

Ordinary classes such as Pipe or Service only need to create instances through a simple new. For instructions and components, a certain environment is required. This is because of Angular's module concept. If you want a component to run, you must first have a @NgModule definition.

The tool set does not contain a lot of information, and you can easily master it. Below I will briefly explain a few of the most commonly used ones:

TestBed

TestBed is provided by the Angular testing tool set for building a @NgModule Test environment module. Of course, with the module, you also need to use TestBed.createComponent to create a test component for testing the target component.

Asynchronous

Asynchronous is everywhere in Angular, and asynchronous testing can use the toolset async, fakeAsync to write elegant tests The code looks synchronous.

There are more tools in the tool set, all of which we will explain one by one in [Angular Unit Testing - Component and Instruction Unit Testing]().

happy coding!

The above is the detailed content of How to set up a test environment? Introduction to Angular testing toolset. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete