


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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool