Diferència entre revisions de la pàgina «Javascript Quality Control with Jest and ESLint»
m |
|||
| (Hi ha 10 revisions intermèdies del mateix usuari que no es mostren) | |||
| Línia 1: | Línia 1: | ||
| + | __TOC__ | ||
=Introducció= | =Introducció= | ||
Referència que seguim, article: Javascript Quality Control with Jest and ESLint | Referència que seguim, article: Javascript Quality Control with Jest and ESLint | ||
*https://medium.com/asos-techblog/javascript-quality-control-with-jest-and-eslint-b888eeb4b0c4 | *https://medium.com/asos-techblog/javascript-quality-control-with-jest-and-eslint-b888eeb4b0c4 | ||
| + | =Getting Started= | ||
| + | *https://jestjs.io/docs/getting-started | ||
| + | |||
| + | Instal·lem jest: | ||
| + | <pre> | ||
| + | $ npm install --save-dev jest | ||
| + | </pre> | ||
| + | |||
| + | El primer de tot és crear el projecte: | ||
| + | <pre> | ||
| + | $ mkdir prova_test | ||
| + | $ cd prova_test | ||
| + | $ npm init | ||
| + | </pre> | ||
| + | script ''sum.js'': | ||
| + | <pre> | ||
| + | function sum(a, b) { | ||
| + | return a + b; | ||
| + | } | ||
| + | module.exports = sum; | ||
| + | </pre> | ||
| + | script ''sum.test.js'': | ||
| + | (només pel fet de tenir extensió ''test.js'', o bé estar dins de la carpeta ''__test__'', ja participarà en el test): | ||
| + | <pre> | ||
| + | const sum = require('./sum'); | ||
| + | |||
| + | test('adds 1 + 2 to equal 3', () => { | ||
| + | expect(sum(1, 2)).toBe(3); | ||
| + | }); | ||
| + | </pre> | ||
| + | El fitxer ''package.json'' s'ha creat en el ''npm init''. La part de test posarem: | ||
| + | <pre> | ||
| + | "scripts": { | ||
| + | "test": "jest" | ||
| + | } | ||
| + | </pre> | ||
| + | i ara ja podem provar el test: | ||
| + | <pre> | ||
| + | $ npm run test | ||
| + | |||
| + | > prova_test@1.0.0 test | ||
| + | > jest | ||
| + | |||
| + | PASS ./sum.test.js | ||
| + | ✓ adds 1 + 2 to equal 3 (4 ms) | ||
| + | |||
| + | Test Suites: 1 passed, 1 total | ||
| + | Tests: 1 passed, 1 total | ||
| + | Snapshots: 0 total | ||
| + | Time: 1.485 s | ||
| + | Ran all test suites. | ||
| + | </pre> | ||
| + | També podem crear la carpeta ''__tests__'', i allà ficar els scripts .js que volem avaluar. Per exemple, ''__tests__/suma.js'': | ||
| + | <pre> | ||
| + | const sum = require('../sum'); | ||
| + | |||
| + | test('adds 5 + 7 to equal 12', () => { | ||
| + | expect(sum(5, 7)).toBe(12); | ||
| + | }); | ||
| + | </pre> | ||
| + | i ara s'executen els dos tests. | ||
| + | |||
| + | o bé més senzill: | ||
| + | <pre> | ||
| + | $ npm test | ||
| + | |||
| + | > prova_test@1.0.0 test | ||
| + | > jest | ||
| + | |||
| + | PASS ./sum.test.js | ||
| + | PASS __tests__/suma.js | ||
| + | |||
| + | Test Suites: 2 passed, 2 total | ||
| + | Tests: 2 passed, 2 total | ||
| + | Snapshots: 0 total | ||
| + | Time: 3.155 s | ||
| + | Ran all test suites | ||
| + | </pre> | ||
| + | Amb l'opció ''--coverage'' la informació és una mica diferent: | ||
| + | <pre> | ||
| + | "scripts": { | ||
| + | "test": "jest --coverage", | ||
| + | } | ||
| + | </pre> | ||
| + | <pre> | ||
| + | $ npm run test | ||
| + | |||
| + | > prova_test@1.0.0 test | ||
| + | > jest --coverage | ||
| + | |||
| + | PASS __tests__/suma.js | ||
| + | PASS ./sum.test.js | ||
| + | ----------|---------|----------|---------|---------|------------------- | ||
| + | File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | ||
| + | ----------|---------|----------|---------|---------|------------------- | ||
| + | All files | 100 | 100 | 100 | 100 | | ||
| + | sum.js | 100 | 100 | 100 | 100 | | ||
| + | ----------|---------|----------|---------|---------|------------------- | ||
| + | |||
| + | Test Suites: 2 passed, 2 total | ||
| + | Tests: 2 passed, 2 total | ||
| + | Snapshots: 0 total | ||
| + | Time: 1.82 s | ||
| + | Ran all test suites. | ||
| + | </pre> | ||
| + | ==Linting amb ESLint== | ||
| + | Lint serveix per: | ||
| + | *Improved readability | ||
| + | *Finding syntax errors before execution | ||
| + | *Disallow unused and undeclared variables | ||
| + | *Solves the tab vs. spaces debate | ||
| + | <pre | ||
| + | $ npm install eslint --save-dev | ||
| + | |||
| + | $ joe .eslintrc | ||
| + | // .eslintrc | ||
| + | { | ||
| + | "env": { | ||
| + | "browser": true, | ||
| + | "es6": true, | ||
| + | "jest": true, | ||
| + | "node": true | ||
| + | }, | ||
| + | "extends": [ | ||
| + | "eslint:recommended" | ||
| + | ] | ||
| + | } | ||
| + | |||
| + | $ joe .eslintignore | ||
| + | node_modules | ||
| + | coverage | ||
| + | </pre> | ||
| + | Afegirm el '''lint''' en el nostre ''package.json'': | ||
| + | <pre> | ||
| + | { | ||
| + | "scripts": { | ||
| + | "lint": "eslint .", | ||
| + | "test": "jest --coverage", | ||
| + | "test:watch": "jest --watch" | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | I podem provar-ho: | ||
| + | <pre> | ||
| + | $ npm run lint | ||
| + | |||
| + | > prova_test@1.0.0 lint | ||
| + | > eslint . | ||
| + | |||
| + | |||
| + | /home/joan/M06_WEC_2021/prova_test/sum.js | ||
| + | 2:5 error 'c' is defined but never used no-unused-vars | ||
| + | |||
| + | ✖ 1 problem (1 error, 0 warnings) | ||
| + | </pre> | ||
| + | Però amb aquestes regles bàsiques per defecte i recomanades no es posa amb la tabulació ni amb el punt i coma al final de les sentències. | ||
=Cas d'us: https://github.com/trekhleb/javascript-algorithms/= | =Cas d'us: https://github.com/trekhleb/javascript-algorithms/= | ||
| Línia 41: | Línia 198: | ||
$ npm test -- 'playground' | $ npm test -- 'playground' | ||
</pre> | </pre> | ||
| + | ==playground== | ||
| + | Primer de tot he hagut d'actualitzar Node a la última versió, la 16: | ||
| + | *[[Mòduls_amb_Javascript#Utilitzar_m.C3.B2duls_a_la_consola._Actualitzar_Node]] | ||
| + | Ara vull fer una prova en el playground per crear una llista enllaçada i afegir-hi dos membres. Per tal de què funcioni, he hagut de fer: | ||
| + | |||
| + | script ''playground.js'': | ||
| + | <pre> | ||
| + | // Place your playground code here. | ||
| + | import LinkedList from '../data-structures/linked-list/LinkedList.js'; | ||
| + | import Comparator from '../utils/comparator/Comparator.js'; | ||
| + | |||
| + | const linkedList = new LinkedList(); | ||
| + | linkedList.append('aaa'); | ||
| + | linkedList.append('bbb'); | ||
| + | console.log(linkedList.reverse().toString()); | ||
| + | </pre> | ||
| + | <pre> | ||
| + | $ node src/playground/playground.js | ||
| + | bbb,aaa | ||
| + | </pre> | ||
| + | Si ens fixem, hem afegit '''.js''' a ''LinkedList'' i ''Comparator'', i això també ho hem hagut de fer en els mòduls als que fem referència (els que estan dins de data-structures/linked-lists''. A més, en el fitxer ''package.json'' hem afegit a sota del main: | ||
| + | <pre> | ||
| + | "main": "index.js", | ||
| + | "type": "module", | ||
| + | </pre> | ||
| + | |||
| + | doncs si no, donava l'error: | ||
| + | <pre> | ||
| + | $ node src/playground/playground.js | ||
| + | (node:8164) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. | ||
| + | (Use `node --trace-warnings ...` to show where the warning was created) | ||
| + | /home/joan/javascript-algorithms/src/playground/playground.js:2 | ||
| + | import LinkedListNode from '../data-structures/linked-list/LinkedListNode'; | ||
| + | ^^^^^^ | ||
| + | |||
| + | SyntaxError: Cannot use import statement outside a module | ||
| + | </pre> | ||
| + | Però almenys ara ja puc utilitzar totes aquestes funcions. Ara bé, hi deu haver una altra manera per no haver de fer aquests canvis. | ||
| + | |||
| + | ==playground (solució)== | ||
| + | *https://github.com/trekhleb/javascript-algorithms/issues/705 | ||
| + | <pre> | ||
| + | I've added some more details to the playground files. The idea is to continue using the test-driven approach for the playground as we use it for the rest of the algorithms. It basically means that instead of running the node src/playground/playground.js directly the user would run npm test -- 'playground' instead. | ||
| + | </pre> | ||
| + | El codi per provar una llista enllaçada quedaria de la següent manera: | ||
| + | |||
| + | script ''playground.js'': | ||
| + | <pre> | ||
| + | import LinkedList from '../data-structures/linked-list/LinkedList'; | ||
| + | |||
| + | // Write your playground code inside the playground() function. | ||
| + | // Test your code from __tests__/playground.test.js | ||
| + | // Launch playground tests by running: npm test -- 'playground' | ||
| + | function playground() { | ||
| + | const linkedList = new LinkedList(); | ||
| + | linkedList.append('aaa'); | ||
| + | linkedList.append('bbb'); | ||
| + | //console.log(linkedList.reverse().toString()); | ||
| + | |||
| + | return linkedList.reverse().toString(); | ||
| + | } | ||
| + | |||
| + | export default playground; | ||
| + | </pre> | ||
| + | script ''playgroundtest.js'': | ||
| + | <pre> | ||
| + | import playground from '../playground'; | ||
| + | |||
| + | describe('playground', () => { | ||
| + | it('should return correct results', () => { | ||
| + | // Replace the next dummy test with your playground function tests. | ||
| + | expect(playground()).toMatch('bbb,aaa'); | ||
| + | }); | ||
| + | }); | ||
| + | </pre> | ||
| + | Finalment: | ||
| + | <pre> | ||
| + | $ npm test -- 'playground' | ||
| + | |||
| + | > javascript-algorithms-and-data-structures@0.0.4 test | ||
| + | > jest "playground" | ||
| + | |||
| + | PASS src/playground/__test__/playground.test.js | ||
| + | |||
| + | Test Suites: 1 passed, 1 total | ||
| + | Tests: 1 passed, 1 total | ||
| + | Snapshots: 0 total | ||
| + | Time: 1.676 s | ||
| + | Ran all test suites matching /playground/i. | ||
| + | </pre> | ||
| + | (podem utilitzar ''console.log()'' per veure la sortida) | ||
{{Autor}}, maig 2021 | {{Autor}}, maig 2021 | ||
Revisió de 10:49, 14 maig 2021
Contingut
Introducció
Referència que seguim, article: Javascript Quality Control with Jest and ESLint
Getting Started
Instal·lem jest:
$ npm install --save-dev jest
El primer de tot és crear el projecte:
$ mkdir prova_test $ cd prova_test $ npm init
script sum.js:
function sum(a, b) {
return a + b;
}
module.exports = sum;
script sum.test.js: (només pel fet de tenir extensió test.js, o bé estar dins de la carpeta __test__, ja participarà en el test):
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
El fitxer package.json s'ha creat en el npm init. La part de test posarem:
"scripts": {
"test": "jest"
}
i ara ja podem provar el test:
$ npm run test > prova_test@1.0.0 test > jest PASS ./sum.test.js ✓ adds 1 + 2 to equal 3 (4 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.485 s Ran all test suites.
També podem crear la carpeta __tests__, i allà ficar els scripts .js que volem avaluar. Per exemple, __tests__/suma.js:
const sum = require('../sum');
test('adds 5 + 7 to equal 12', () => {
expect(sum(5, 7)).toBe(12);
});
i ara s'executen els dos tests.
o bé més senzill:
$ npm test > prova_test@1.0.0 test > jest PASS ./sum.test.js PASS __tests__/suma.js Test Suites: 2 passed, 2 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 3.155 s Ran all test suites
Amb l'opció --coverage la informació és una mica diferent:
"scripts": {
"test": "jest --coverage",
}
$ npm run test > prova_test@1.0.0 test > jest --coverage PASS __tests__/suma.js PASS ./sum.test.js ----------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------|---------|----------|---------|---------|------------------- All files | 100 | 100 | 100 | 100 | sum.js | 100 | 100 | 100 | 100 | ----------|---------|----------|---------|---------|------------------- Test Suites: 2 passed, 2 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 1.82 s Ran all test suites.
Linting amb ESLint
Lint serveix per:
- Improved readability
- Finding syntax errors before execution
- Disallow unused and undeclared variables
- Solves the tab vs. spaces debate
Afegirm el '''lint''' en el nostre ''package.json'':
<pre>
{
"scripts": {
"lint": "eslint .",
"test": "jest --coverage",
"test:watch": "jest --watch"
}
}
I podem provar-ho:
$ npm run lint > prova_test@1.0.0 lint > eslint . /home/joan/M06_WEC_2021/prova_test/sum.js 2:5 error 'c' is defined but never used no-unused-vars ✖ 1 problem (1 error, 0 warnings)
Però amb aquestes regles bàsiques per defecte i recomanades no es posa amb la tabulació ni amb el punt i coma al final de les sentències.
Cas d'us: https://github.com/trekhleb/javascript-algorithms/
Aquest repositori conté una col·lecció gran d'estructures de dades i algorismes per a Javascript. Cada algorisme conté la seva implementació, documentació i un test per comprovar que el codi és vàlid.
Clonem el repositori $ git clone https://github.com/trekhleb/javascript-algorithms.git How to use this repository Install all dependencies $ npm install Run ESLint: You may want to run it to check code quality. $ npm run lint Run all tests $ npm test Run tests by name $ npm test -- 'LinkedList' Troubleshooting: In case if linting or testing is failing try to delete the node_modules folder and re-install npm packages: $ rm -rf ./node_modules $ npm i Playground You may play with data-structures and algorithms in ./src/playground/playground.js file and write tests for it in ./src/playground/__test__/playground.test.js. Then just simply run the following command to test if your playground code works as expected: $ npm test -- 'playground'
playground
Primer de tot he hagut d'actualitzar Node a la última versió, la 16:
Ara vull fer una prova en el playground per crear una llista enllaçada i afegir-hi dos membres. Per tal de què funcioni, he hagut de fer:
script playground.js:
// Place your playground code here.
import LinkedList from '../data-structures/linked-list/LinkedList.js';
import Comparator from '../utils/comparator/Comparator.js';
const linkedList = new LinkedList();
linkedList.append('aaa');
linkedList.append('bbb');
console.log(linkedList.reverse().toString());
$ node src/playground/playground.js bbb,aaa
Si ens fixem, hem afegit .js a LinkedList i Comparator, i això també ho hem hagut de fer en els mòduls als que fem referència (els que estan dins de data-structures/linked-lists. A més, en el fitxer package.json hem afegit a sota del main:
"main": "index.js", "type": "module",
doncs si no, donava l'error:
$ node src/playground/playground.js (node:8164) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. (Use `node --trace-warnings ...` to show where the warning was created) /home/joan/javascript-algorithms/src/playground/playground.js:2 import LinkedListNode from '../data-structures/linked-list/LinkedListNode'; ^^^^^^ SyntaxError: Cannot use import statement outside a module
Però almenys ara ja puc utilitzar totes aquestes funcions. Ara bé, hi deu haver una altra manera per no haver de fer aquests canvis.
playground (solució)
I've added some more details to the playground files. The idea is to continue using the test-driven approach for the playground as we use it for the rest of the algorithms. It basically means that instead of running the node src/playground/playground.js directly the user would run npm test -- 'playground' instead.
El codi per provar una llista enllaçada quedaria de la següent manera:
script playground.js:
import LinkedList from '../data-structures/linked-list/LinkedList';
// Write your playground code inside the playground() function.
// Test your code from __tests__/playground.test.js
// Launch playground tests by running: npm test -- 'playground'
function playground() {
const linkedList = new LinkedList();
linkedList.append('aaa');
linkedList.append('bbb');
//console.log(linkedList.reverse().toString());
return linkedList.reverse().toString();
}
export default playground;
script playgroundtest.js:
import playground from '../playground';
describe('playground', () => {
it('should return correct results', () => {
// Replace the next dummy test with your playground function tests.
expect(playground()).toMatch('bbb,aaa');
});
});
Finalment:
$ npm test -- 'playground' > javascript-algorithms-and-data-structures@0.0.4 test > jest "playground" PASS src/playground/__test__/playground.test.js Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.676 s Ran all test suites matching /playground/i.
(podem utilitzar console.log() per veure la sortida)
creat per Joan Quintana Compte, maig 2021