jest - GradedJestRisk/js-training GitHub Wiki
List:
Is it right to install jest globally ? Anyway, if using vscode, add jest extension.
Steps:
- create a directory
mkdir PROJECT_NAME - init project
npm init --y - install jest:
- global (evil):
- install
npm install jest --global - set up jest
jest --init
- install
- local:
npm install --save-dev jest
- global (evil):
- commit
- if using vscode :
- open folder and create a workspace
- make sur jest extension is alive (bottom bar)
Add file sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
Add file sum.test.js
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Launch tests:
- in command-line:
- all tests:
npm run test - one test:
npx jest <FILE-PATH>
- all tests:
- if using vscode, click on Jest on btton bar
> jest PASS ./sum.test.js √ adds 1 + 2 to equal 3 (3ms)
If using vscode with Jest extension, add a new test
test('adds 1 + A to be 1', () => {
expect(sum(1, 'A')).toBe(3);
});
It should fail, you should get a red dot on the left of the test's name.
When you change the test/code to get a correct expectation, the test may remain red.
Fire it forcefully by saving file (Ctrl+ S).
describe is a function whose parameters are:
- a string, the test suite description, eg: "functional programming syntax "
- an anonymous function, that contains test cases functions
test is a function whose parameters are:
- a string, the test description, eg: "reduce() applies an operator on all elements"
- an arrow function, that contains an expect method
expect is a function :
- whose parameter is an expression.
- that returns an object ?
toBe is a function on object :
- whose parameter is an expression.
- that returns true if the expression evaluated on object is true
You check it using vanilla JS, then fail in case.
Use fail('I shoulnd't be there..');
test('throws on octopus', () => {
function drinkOctopus() {
drinkFlavor('octopus');
}
expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor'));
});
Extensions:
Overview:
- create suite with desc
- create test with test
- code your first failing test
- make your first code pass
- (stuck in red light ? discard all changes Shift Ctrl S)
- stage/commit with Control S
- refactor
- stage/commit with Control S
- stage (all) changes: Control Shift A
- get focus on commit zone: Ctrl 0
- enter commit comment and save: Ctrl S