search
HomeWeb Front-endJS Tutoriale2e test example in angularjs_AngularJS

In the previous article, we talked about ng’s unit testing. Today, let’s talk about e2e (end-to-end) testing.

When we test a single function point of a module, unit testing is most suitable. However, when bugs occur when users interact with multiple pages, unit testing will not work. At this time, e2e must be used to simulate users. Operation restores the problem site. Of course, e2e testing can also be used to test the robustness of the program. Many things that unit testing cannot do, e2e testing can do.

Before, ng used Angular Scenario Runner to run e2e tests, but now it has been replaced by Protractor to run e2e.

Protractor

Protractor is a framework used in Angularjs to test e2e. It itself is an npm module and is built internally on WebDriverJS. Protractor can truly allow your test cases to run on the browser. Completely simulate the real behavior of users.

Some of its resource addresses are posted below:

1.Test api provided by Protractor
2.ProtractorSimple usage example
3.WebDriverJs guide, this is the core that Protractor depends on, the npm module is called selenium-webdriver

Protractor operating principle

Protractor mainly relies on the following things to run e2e tests:

1.WebDriver APIs, the WebDriverJs mentioned above, are related js apis provided by Selenium for front-end testing
2. Selenium Server, a back-end jar package used to communicate with the browser driver
3.WebDriver browser drivers, used to display real website content and communicate with Selenium Server. This is where the real browser operations are transmitted

The entire operation process is as shown below

If you want to know more about the previous interactions between these components, you can Click here

Use the ng seed project to explain e2e

We use the seed project provided by ng official to explain a real e2e example. First, use the following command to obtain the seed project

Copy code The code is as follows:

git clone https://github.com/angular/angular-seed.git

Then run

Copy code The code is as follows:

npm install

Install all related dependency files

Here we first talk about the configuration files needed to run e2e tests. You can see that the test/protractor-conf.js file is used to configure related functions. Let’s focus on a few properties

1.specs represents the path of the test file to be run, here it is e2e/*.js
2.baseUrl represents the root address of the jump page between browsers in the test file
3.capabilities represents which browser to use to run the test case. For example, if you use chrome, you can set it like this

Copy code The code is as follows:

capabilities: {
'browserName': 'chrome'
}

framework represents which testing framework is used, the one used here is jasmine

If you want to know more about this configuration file, you can Click here to view

After talking about the configuration file, let’s take a look at how to write test cases. First, paste an example from the official website

Copy code The code is as follows:

'use strict';

/* https://github.com/angular/protractor/blob/master/docs/getting-started.md */

describe('my app', function() {

  browser.get('index.html');
  it('should automatically redirect to /view1 when location hash/fragment is empty', function() {
    expect(browser.getLocationAbsUrl()).toMatch("/view1");
  });


  describe('view1', function() {

    beforeEach(function() {
      browser.get('index.html#/view1');
    });


    it('should render view1 when user navigates to /view1', function() {
      expect(element.all(by.css('[ng-view] p')).first().getText()).
        toMatch(/partial for view 1/);
    });

  });


  describe('view2', function() {

    beforeEach(function() {
      browser.get('index.html#/view2');
    });


    it('should render view2 when user navigates to /view2', function() {
      expect(element.all(by.css('[ng-view] p')).first().getText()).
        toMatch(/partial for view 2/);
    });

  });
});


 
首先上面的语法是jasmine框架支持的写法,不了解它的用法的可以点击这里 

这里只说下上面例子里关于protractor提供的一些常用方法与属性

1.browser,全局对象,代表当前浏览器的一个实例,常用的get方法用来实现浏览器改变地址
2.element,全局对象,提供像jquery里负责查找文档元素的功能,常于by对象联合使用
3.by, 全局对象,提供一个选择器类型,比如可以通过css,model,bind等特性来查找一个元素

关于element与by的方法可以参考上面的protractor api文档

说了这么多,该跑一跑上面的测试用例了,命令比较简单

复制代码 代码如下:

npm run update-webdriver

这个负责下载相关的浏览器驱动与selenium-server 本地jar包,一般情况下这个都是会失败的,因为这两个资源都在google服务器那,所以可以利用浏览器翻墙单独下载,地址如下:

1.Chrome Driver地址,一般下载chromedriver_2.9.zip这个文件.

2.selenium-server 本地jar包 下载,一般下载selenium-server-standalone-2.40.0.jar这个文件.

然后把selenium-server拷到protractor包里的selenium文件夹里去,假如上面的命令超时之后,这里也会出现文件不过是空的,直接替换就可以;还要把chromedriver_2.9.zip解压之后的文件拷到这里

最后运行下面的命令可以看到测试结果了

复制代码 代码如下:

npm run protractor

想了解更多关于ng种子项目里的命令行,可以点击这里查看

总结

ng的e2e测试要比单元测试配置要繁琐的多,不过它能做的事情也很多,非常值的你也试一试,有什么问题可以回复到评论里去.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft