Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of front-end Vue unit testing

2025-03-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the knowledge points of front-end Vue unit testing". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

First, why do you need unit testing

Unit testing is used to test the functions of a module in a project, such as functions, classes, components, and so on. Unit tests serve the following purposes:

Correctness: you can verify the correctness of the code and make more detailed preparations before launch

Automation: test cases can be integrated into code version management to automatically perform unit tests to avoid each manual operation

Explanation: can provide other developers with documentation reference for the modules under test, and reading test cases may be more complete than documentation.

Drive development and guide design: unit tests written in advance can not only guide the API design of development, but also find problems in the design in advance.

Ensure refactoring: test cases can be validated multiple times, saving a lot of time when regression testing is needed.

Second, how to write unit tests

Testing principle

When testing code, only consider testing, not internal implementation

The data try to simulate reality, and the closer to reality, the better.

Fully consider the boundary conditions of the data

Focus on testing key, complex, and core code

The combination of testing and functional development is conducive to design and code refactoring.

Writing steps

Preparation phase: construction parameters, creation of spy, etc.

Execution phase: execute the code under test with the constructed parameters

Assertion phase: compare the actual results with the expected results to determine whether the test is normal or not

Clean-up phase: clean up the impact of the preparation phase on the external environment, remove spy created in the preparation phase, etc.

Third, testing tools

Unit testing tools can be divided into three categories:

Test runner (Test Runner): can simulate a variety of browser environments, custom configuration test framework and assertion libraries, such as Karma.

Testing framework: functional modules that provide unit testing. Common frameworks include Jest, mocha, Jasmine, QUnit.

Tool library: assert, should.js, expect.js, chai.js and other assertion libraries, enzyme rendering library, Istanbul coverage calculation.

Here, we will use Jest as an example. Jest has comprehensive functions, integrates various tools, and is easy to configure, even zero configuration is used directly.

IV. Introduction to Jest

The description of Jest's official website is as follows:

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

Installation

Yarn add-- dev jest# or# npm install-D jest simple example

Starting with the example provided on the official website, test a function that completes the addition of two numbers and creates a sum.js file:

Function sum (a, b) {return a + b;} module.exports = sum

Then, create the sum.test.js file:

Const sum = require ('. / sum'); test ('adds 1 + 2 to equal 3, () = > {expect (sum (1,2)) .tobe (3);}); add a test task to package.json: {"scripts": {"test": "jest"}}

Finally, run yarn test or npm run test, and Jest will print the following message:

PASS. / sum.test.js

✓ adds 1 + 2 to equal 3 (5ms)

At this point, a basic unit test is completed.

Note: Jest simulates a real browser in a Node virtual browser environment by using JSDOM, and because js is used to simulate DOM, Jest cannot test the style. The Jest test runner automatically sets JSDOM.

Jest Cli

You can run Jest directly from the command line (provided that jest has been added to the environment variable PATH, such as Jest installed through yarn global add jest or npm install jest-global) and specify various useful configuration items for it. Such as:

Jest my-test-notify-config=config.json

The Jest command has the following common parameters:

-- coverage indicates the output unit test coverage. The coverage file defaults to tests/unit/coverage/lcov-report/index.html.

-- watch snooping mode, unit tests are retriggered when files related to test cases are changed.

For more options, see Jest CLI Options.

Use Profil

Use the jest command to generate a configuration file:

Jest-init

There are several options for you to choose from:

√ Would you like to use Typescript for the configuration file?... No

√ Choose the test environment that will be used for testing »jsdom (browser-like)

√ Do you want Jest to add coverage reports?... Yes

√ Which provider should be used to instrument code for coverage? »babel

√ Automatically clear mock calls and instances between every test?... Yes

Example of a profile (not based on the above selection):

/ / jest.config.jsconst path = require ('path') module.exports = {preset:' @ vue/cli-plugin-unit-jest/presets/typescript-and-babel', rootDir: path.resolve (_ _ dirname,'. /'), coverageDirectory:'/ tests/unit/coverage', collectCoverageFrom: ['src/*. {js,ts,vue}', 'src/directives/*. {js,ts,vue}' 'src/filters/*. {js,ts,vue}', 'src/helper/*. {js,ts,vue}', 'src/views/**/*. {js,ts,vue}', 'src/services/*. {js,ts,vue}'} use Babel

Yarn add-- dev babel-jest @ babel/core @ babel/preset-env

You can create a babel.config.js file under the root of the project to configure Babel that is compatible with your current Node version:

/ / babel.config.jsmodule.exports = {presets: [['@ babel/preset-env', {targets: {node: 'current'}}]],}; use Jest in vue-cli

You can use Jest in vue-cli by installing the @ vue/cli-plugin-unit-jest plug-in in your project:

Vue add unit-jest# or# yarn add-D @ vue/cli-plugin-unit-jest @ types/jest "scripts": {"test:unit": "vue-cli-service test:unit-- coverage"}

@ vue/cli-plugin-unit-jest will inject the command test:unit into the vue-cli-service, and the following files will be recognized by default: / (tests/unit/**/*.spec. (js | jsx | ts | tsx) | * * / _ tests__/*. (js | jsx | ts | tsx)) performs the unit test, that is, the file at the end of the .spec. (js | jsx | ts | tsx) in the tests/unit directory and all js (x) / ts (x) files in the directory name _ _ tests__.

Common examples

The judgment value is equal.

ToBe () checks whether the two basic types match exactly:

Test ('two plus two is four', () = > {expect (2 + 2) .tobe (4);})

ToEqual () checks whether the object is equal:

Test ('object assignment', () = > {const data = {one: 1}; data [' two'] = 2; expect (data). ToEqual ({one: 1, two: 2}); check the false value

ToBeNull only matches null

ToBeUndefined only matches undefined

ToBeDefined is the opposite of toBeUndefined

ToBeTruthy matches any if statement to be true

ToBeFalsy matches any if statement is false

Example:

Test ('null', () = > {const n = null; expect (n). ToBeNull (); expect (n). ToBeDefined (); expect (n). Not.toBeUndefined (); expect (n). Not.toBeTruthy (); expect (n). ToBeFalsy ();}); test (' zero', () = > {const z = 0; expect (z). Not.toBeNull (); expect (z). ToBeDefined (); expect (z). Not.toBeUndefined () Expect (z). Not.toBeTruthy (); expect (z). ToBeFalsy ();}); digit size comparison

Test ('two plus two', () = > {const value = 2 + 2; expect (value) .toBeGreaterThan (3); expect (value) .toBeGreaterThanOrEqual (3.5); expect (value) .toBeLessThan (5); expect (value) .toBeLessThanOrEqual (4.5); / / toBe and toEqual are equivalent for numbers expect (value) .tobe (4); expect (value) .toEqual (4);})

For comparing floating point equality, use toBeCloseTo instead of toEqual, because you don't want the test to depend on a small rounding error.

Test ('addition of two floating point numbers', () = > {const value = 0.1 + 0.2; / / expect (value) .tobe (0.3); this sentence will report an error because the floating point number has a rounding error expect (value). ToBeCloseTo (0.3); / / this sentence can run}); string comparison

You can use regular expressions to check:

Test ('there is no I in team', () = > {expect (' team'). Not.toMatch (/ I /);}); test ('but there is a "stop" in Christoph', () = > {expect (' Christoph'). ToMatch (/ stop/);}); arrays and class arrays

You can use toContain to check whether an array or iterable object contains a particular item:

Const shoppingList = ['diapers',' kleenex', 'trash bags',' paper towels', 'milk',]; test (' the shopping list has milk on it', () = > {expect (shoppingList) .toContain ('milk'); expect (new Set (shoppingList)). ToContain (' milk');}); exception

It can also be used to check whether a function throws an exception:

Function compileAndroidCode () {throw new Error ('you are using the wrong JDK');} test (' compiling android goes as expected', () = > {expect () = > compileAndroidCode ()). ToThrow (); expect (() = > compileAndroidCode ()) .toThrow (Error); / / You can also use the exact error message or a regexp expect (() = > compileAndroidCode ()) .toThrow ('you are using the wrong JDK'); expect () = > compileAndroidCode ()). ToThrow (/ JDK/);})

Refer to the API documentation for more usage.

Execute only the current test

You can use the only () method to indicate that only this test is executed, reducing unnecessary repetitive testing:

Test.only ('it is raining', () = > {expect (inchesOfRain ()) .toBeGreaterThan (0);}); test ('it is not snowing', () = > {expect (inchesOfSnow ()) .tobe (0);}); Test asynchronous code

Callback function

For example, suppose you have a fetchData (callback) function that takes some data and calls callback (data) when it's done. The data you expect to return is a string 'peanut butter':

Test ('the data is peanut butter', done = > {function callback (data) {try {expect (data) .tobe (' peanut butter'); done ();} catch (error) {done (error);}} fetchData (callback);})

Done () is used to indicate that the test execution is complete. Without this done (), our unit test ends after the test execution, which is not in line with our expectations, because the callback has not yet been called and the unit test is not finished. If the done () function has never been called, a timeout error will be prompted.

If expect fails, it throws an error and the subsequent done () no longer executes. If we want to know why the test case failed, we must put expect in try and pass error to the done function in catch. Otherwise, the final console will show a timeout error failure, unable to display the value we received in expect (data).

Promises

Or use the above example:

Test ('the data is peanut butter', () = > {return fetchData () .then (data = > {expect (data) .tobe (' peanut butter');});})

Don't forget the return results to ensure that testing and functionality end at the same time.

If you expect Promise to be reject, use the catch method:

Test ('the fetch fails with an error', () = > {expect.assertions (1); return fetchData () .catch (e = > expect (e) .toMatch (' error'));})

You can also use resolves and rejects matchers:

Test ('the data is peanut butter', () = > {return expect (fetchData ()) .scientives.toBe (' peanut butter');}); test ('the fetch fails with an error', () = > {return expect (fetchData ()) .Rejects.toMatch (' error');}); Async/Await

Test ('the data is peanut butter', async () = > {const data = await fetchData (); expect (data) .tobe (' peanut butter');}); test ('the fetch fails with an error', async () = > {expect.assertions (1); try {await fetchData ();} catch (e) {expect (e) .toMatch (' error');}}))

Async/await can also be used with resolves () / rejects ():

Test ('the data is peanut butter', async () = > {await expect (fetchData ()) .collecves.toBe (' peanut butter');}); test ('the fetch fails with an error', async () = > {await expect (fetchData ()) .Rejects.toMatch (' error');}); installation and removal

Before and after testing

In some cases, we need to do some preparatory work before we start the test, and then after the test is complete, to do some cleaning work, we can use beforeEach and afterEach.

For example, we need to initialize some city data before each test, and clean it up after the test:

BeforeEach (() = > {initializeCityDatabase ();}); afterEach (() = > {clearCityDatabase ();}); test ('city database has Vienna', () = > {expect (isCity (' Vienna')). ToBeTruthy ();}); test ('city database has San Juan', () = > {expect (isCity (' San Juan')). ToBeTruthy ();})

Similarly, beforeAll and afterAll perform a single execution before and after the start and end of the current spec test file.

Test case grouping

By default, blocks of before and after can be applied to each test in the file. In addition, tests can be grouped by describe blocks. When the blocks of before and after are inside the describe block, they are only applicable to tests within that describe block.

/ / Applies to all tests in this filebeforeEach (() = > {return initializeCityDatabase ();}); test ('city database has Vienna', () = > {expect (isCity (' Vienna')). ToBeTruthy ();}); test ('city database has San Juan', () = > {expect (isCity (' San Juan')). ToBeTruthy ();}); describe ('matching cities to foods', () = > {/ Applies only to tests in this describe block beforeEach () = > {return initializeFoodDatabase ();})) Test ('Vienna

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report