As a front end, did not know the benefits of unit testing at the beginning, feel laborious, effect is not obvious, also to have a module for performance issues for a refactoring, exhausted by the time, only to find that the benefits of unit testing, can say, a unit test, to face the other colleagues to write code or n years ago, Feel free to continue to maintain and even rebuild it.
- Unit testing differs from integration testing in that it checks and validates the smallest testable unit (typically a single function or widget). The best results will be achieved if the functionality is as simple as possible and the impact of a single validation variable is as small as possible. Good unit test cases serve as development documentation for future generations to read.
Assertions library chai
At its heart, unit testing is all about assertions, which tell you whether your code is doing what it’s trying to do
Node has built-in assertions to assert. The simplest example is shown below, which throws an exception if an error occurs
The CHAI assertion library is full and powerful, providing the commonly used Assert Should Expect assertion keyword
All kinds of usage is not mentioned, the method is relatively simple, a check will know. Assert is the simplest, but expect uses it a lot these days, for exampleexpert(xxx).toBe(xxxx)
butThe egg’s official websiteAssert is recommended because it’s simple and you don’t have to remember some complicated API.
Mocha
Mocha is an old library, simple and easy to use. At present, the company is using Mocha+ CHAI to test front-end data logic, which can be used to test functions in Node and util. Test components need to be matched with other frameworks.
Mocha provides four hooks for test cases in the Describe block: before(), after(), beforeEach(), and afterEach(). Before hooks can be used to prepare the test environment and data in advance, and beforeEach hooks can prepare one or more new objects before each test case to prevent contamination by previous use cases
Describe (' test index.js',()=> {before(()=>console.info(" executed before all test cases in this block ")) after(()=>console.info(" executed after all test cases in this block ")) BeforeEach (()=>console.info(" executed beforeEach test case in this block ") afterEach(()=>console.info(" executed afterEach test case in this block ")) describe(' test addNum function ', () = > {it (' two together the results for two Numbers and ', () = > {assert. Equal (addNum (1, 2), 3)})})})Copy the code
Finally, by default, Mocha executes at most 2000 milliseconds per test case, and if no results are returned by then, an error is reported, and Mocha by default highlights test cases that exceed 75 milliseconds, which can be modified
sinon
Sinon has three distinctive functions of Spies, stub and mock. Those who are interested can try to realize it by hand.
- The concept of very soon
Spies => Spy function. Spy function is the simplest part of Sinon. Other functions are based on Spies. The implementation of Spies monitored on the basis of not affecting the normal invocation of the function itself (the context of the monitored function was not affected).
- The concept of a stub
Stub completely replaces this function and has all the functionality of Spies. When a stub is used, the function does not have the original function, but the replacement function.
- The concept of the mock
Mocks, like stubs, can be used to replace specified functions. If you want to replace multiple methods on an object, mocks can be useful. However, if you want to replace only one function on an object, stubs are much easier to use and you should be careful when using mocks. Because of the large number of replacement of the original code logic, test will become fragile.
Nock or moxios
Used to simulate sending network requests and to replace background interfaces.
Karma
Non-jsdom, provides a real browser environment, due to the current various frameworks have been relatively perfect, now has been basically excluded from the mainstream framework
redux-mock-store
As the name suggests, used to simulate a Store in Redux. I’m not going to go into this because I’ve been working with Mobx
jasmine
Similar to jEST, which used to work with Karma, large and comprehensive testing frameworks (JEST) have been used less as they have gone mainstream
jest
Jest is a facebook testing framework that integrates Mocha, Chai, Jsdom, Sinon, and more. So if you’re just getting started you can go to JEST.
React scaffolding comes with JEST. Vue-cli3.0 also integrates with the unit testing framework. It will ask you to choose Mocha + Chai or JEST.
- Running jest automatically runs all.test.js and.spec.js files in the project. Jest can be configured in package.json by default, for example, test only the test. JSX file in the test folder
"jest": {
"testRegex": "/test/*.test.jsx?$"
}
Copy the code
-
Integrating Expect assertions
-
Asynchronous processing is done() for callback to ensure completion of the test, and is automatically processed for promise, reject and async+await
-
Mock in Jest,
Sinon is similar to sinon, and can also simulate axios’ network request
-
Snapshot Generates a snapshot for components or data. Each test is automatically compared. An error occurs if the data is inconsistent
-
You can generate test coverage reports by adding –coverage after the jest command
jest --coverage
Copy the code
enzyme && test-utils
The enzyme launched by Airbnb is specially used to test the React component. Corresponding to vUE, there is also the test-utils package, which basically has the same function and determines the event trigger and element existence after the component is mounted.
The enzyme mainly provides three rendering methods: render, mount and shallow, with the following differences:
Shallow and mount components render the react tree. If you’ve used chrome’s React DevTool plugin, the render result is the same as the react DevTool TAB.
Shallow and mount return a encapsulated ReactWrapper that can perform multiple JQ-like chain operations, such as find(), parents(), children(), and other selectors for element lookup. State() and props() perform data lookup, and setState() and setprops() operate data; Simulate () Triggers the simulation event.
Shallow renders only the current component, asserts only the current component, and does not produce child components; Mount renders the current component and all its children, and can do the same for all children. Most interaction tests care about subcomponents, and I used mount. However, mounting takes longer and consumes more memory, so shallow is generally used if it is not necessary to manipulate and assert child components.
React Testing Library allows you to use the react Testing Library instead of the react Testing Library.
conclusion
Unit test is a work that requires input but can’t see the output, so directly choosing the most concise framework to save time is the key to improve KPI. Now the framework tends to be more and more simple and humanized, so if used in work, it is good to directly choose the JEST class integration framework.
At toB, the traditional software services company I work for, front-end stability is more important. After a rapid iteration period of a product, unit testing will also gradually cover util module and Model layer (data change processing in response to action), and the rest will depend on the iteration schedule, as well as basic common components that are often reconstructed. Each company has different needs, so if it’s a go-live, go project, you don’t need to deploy tests. So before you consider introducing unit testing, be flexible about costs and benefits.