foreplay
Recently wrote a small project for Wechat – ColorPicker. Mainly just to practice TS. Since I have written a small library, I thought it would be interesting to learn how to write tests.
It took nearly 2 hours from the selection to the construction of the environment. It has to be said that a qualified front end is a qualified configuration engineer. Again, the tools needed to build the configuration for this project.
- Webpack. config automatically compiles TS + CSS
- Tsconfig. config Indicates the ts configuration file
- Tslint. json TsLint configuration file
- Jest. Config configuration jest
- .babelrc Jest will also need plug-ins when parsing JS
- Circle. yml CircleCI configuration file
If you do not understand what, their own baidu
Getting started with Jest + TS
First question, my project is written by TS, so what should I do about the syntax like import?
Ts-jest can be found at the bottom of Getting Started on the website. It is easy to understand that we need to configure what type of file jEST is loaded into and what preprocessing is used to process the file.
transform: {
'.*\\.(ts)$': '<rootDir>/node_modules/ts-jest/preprocessor.js',},Copy the code
Transform is designed to match various file suffixes and preprocess them. You can think of it as a Loader in webpack
What if I introduced a.css file in TS? Same as above
Now that we have a transform, any file can be preprocessed by a transform.
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest'.'.*\\.(ts)$': '<rootDir>/node_modules/ts-jest/preprocessor.js'.'^.+\\.(css)$':"<rootDir>/node_modules/jest-css-modules"
},
Copy the code
If it’s a JS file and I’m working with babel-jest, CSS uses jest-CSS-modules. If you don’t have these configurations, then importing your library, js files or CSS files that introduce high features will compile errors.
About rootDir
During the selection process, I looked at the latest vuE-CLI framework recommended for testing, jest and Krama + Mocha. I chose Jest. Jest itself is created by FB and is very react friendly. There is also a lot of environment encapsulation itself to switch jsDOM or Node environment is very convenient. I finally chose this one.
I just started looking at the Jest configuration in vue-CLI and I rejected it. The first and most obvious keyword is something like
that looks like XML. But when you slow down, it’s easy to understand that it’s a basePath. We can look at the documentation and say rootDir
My catalog is as follows
--- __test__
jest.config.js
--- dist
--- node_modules
--- src
Copy the code
//jest.config.js
module.exports = {
rootDir: path.resolve(__dirname, '.. / '),}Copy the code
actually represents the root directory
SetupFiles options
SetupFiles is an AOP configuration, I think this is very useful! Because jest is through jsDOM is to simulate a Document execution environment, there must be a lot of possible not, such as localStorage, then we can use this configuration to set what we need to load before we start, For example, in vue-CLI, vue.config. productionTip = false, and we can make the environment support localStorage.
setupFiles: ["jest-localstorage-mock"]
Copy the code
It is not difficult to find, in fact, JEST’s ecology is very rich, I encountered this problem Google a few keywords can be quickly solved
How do I write UI Test?
UI test is coupled to the Dom on the one hand and the user interaction on the other.
The idea is: simulate user operations, and then use Dom to determine whether the rendering is correct.
For example, the instantiation test, we can test whether the initialization is normal, using jquery to help determine
// Instantiate the test
import WeChatColorPicker from '.. /src';
import $ from 'jquery';
export function newInstance() {
document.body.innerHTML = `<div id="container"></div>`;
return new WeChatColorPicker(pickerOptions);
}
constbaseColorArr = [ ... ] ; test('test new instance', () = > {const instance = newInstance();
expect(instance.baseComponent.baseColorArr).toEqual(baseColorArr);
expect($('.wechat-colorpicker')).not.toBeNull();
});
Copy the code
For example, if I hit Basic color, more colors, and we’re going to toggle class, I can go like this
// Interactive test of TAB class switching
import $ from 'jquery';
import { newInstance } from './utils';
describe('change tab test', () => {
newInstance();
test('use base color', () => {$()'.wechat-picker-box p i').eq(0).click();
expect($('.wechat-colorpicker').hasClass('base-color')).toBe(true);
});
test('use picker', () => {$()'.wechat-picker-box p i').eq(1).click();
expect($('.wechat-colorpicker').hasClass('more-color')).toBe(true);
});
});
Copy the code
Does it suddenly feel so easy? And is unique, test case reliability is also guaranteed. After that, we only need to cooperate with one CI and run away our test code before each submission. If all use cases are successfully tested, pr will be issued, otherwise they will be directly rejected.
After writing the test, add one more line to our jest. Config to generate our test report.
module.exports = {
// ...
collectCoverage: true.// ...
}
Copy the code
Then run NPM t to see the test result as follows
- % Stmts is statement coverage: is every statement executed?
- % Branch coverage: Is every if block executed?
- % Funcs function coverage: Is every function called?
- % Lines line coverage: Is every line executed?
For more test cases, go to >>> repo-video-colorpicker <<<
CricleCI
We can use CI tools to improve our WordFlow, and I’m using CricleCi here. Go to the official website and setup our project directly after logging in to Github.
Then add a cricle.yml to our project root directory and copy and paste its recommended configuration.
Then let’s test push, where I miswrote my file path, so the build reported an error.
After fixing the problem, you can work normally.
Since this article is not focused on CI, here is not more than the expansion, interested friends can explore their own
There’s really no back there
At this point, you should have a general understanding of front-end UI testing.
This article does not introduce the usage or syntax of Jest too much, I hope it can give some direction to friends who do not know how to do testing, try to find their own project is the best.
It can be hard to get started, it can be difficult, it can be expensive. In fact, it is a slow routine, writing proficiently should be addictive, after all, the feeling of finishing the test will make you reach an orgasm.