“This is the 24th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Jest — Coverage jest — Coverage jest — Coverage jest –coverage Of course, if you haven’t already set up a JEST environment, you can, because the proof is in the pudding. A quick build environment article is posted below: Jest | Test Framework practice – Basics and build environments.
Write test cases
There are many tutorials and official examples on how to write test cases, so here we will only write two very common test cases for synchronous and asynchronous code.
- Synchronization code
// sum.test.ts const sum = (a:number, b:number) => a + b test(' count ', () => {// Conclude that 1 + 1 = 2 expect(sum(1, 1)) 1)).toBe(2) })Copy the code
- Asynchronous code
// async.test.ts const getData = (type: string) => type === 'get'? Promise. Resolve (1):Promise. Reject (2) test(' test async ', async () => {expect. Assertions (1); await expect(getData('get')).resolves.toEqual(1) })Copy the code
For more information on how to write test cases for more scenarios, go to the official website. Here’s how to interpret coverage.
Interpreting coverage
When we execute jest –coverage we generate coverage folder coverage in the current file as follows:
That’s when we can findlcov-report/index.html
File, and then open it in a browser, at which point we can see the test case writing coverage for the current project. Here’s an example of a tool library I wrote:
The table lists all the test cases of the utility class library, with several indicators:
- Statements coverage, which corresponds to js syntactic Statements that parse into ast numbers of type
statement
. - Coverage rate of Branches
if/else
This kind of condition - Function coverage
- Lines Coverage is how many Lines of code are executed
In the file, we find that the coverage of Branches in urL-utils files is not high, reaching 64.29%. Then how to check which codes are not covered? Very simple, click the corresponding file name to enter the view, the effect is as follows:
The yellow bars in the diagram represent ways that the test case did not test, but of course you can also press shortcut keysn
orj
To see the next block of code that is not covered. The yellow block in the figure is not covered by conditional statements, which meet the test coverage of Branchs.
conclusion
At this point, the completion of the basic test case writing, as well as test case generation, and can see how the test case coverage, in order to improve the overall test case writing, to help the code to achieve the purpose of perfect and robust. What is the rationale for how coverage is generated? I’ll talk about that in the next post.