In this course we use Jest for testing.
To get started, well... follow the instruction at the getting started page: https://jestjs.io/docs/en/getting-started.html
Repository used in class: https://github.com/2018-Trento-SEII-INFORG/TestingAndCI
"scripts": {
"test": "jest"
}
package.json
:"jest": {
"verbose": true,
"collectCoverage": true
}
someModule.js
:function concatenateStrings (a,b) {
return a+b
}
module.exports = { conc: concatenateStrings}
someModule.test.js
:const conc = require('./someModule').conc
test('multiply 2', () => {
expect(4).toBe(4);
});
test('concat test', () => {
expect(conc('a','b')).toBe('ab');
});
test('concat null', () => {
expect(conc(null,null)).toBe(0);
});
npm test
Online documentation: https://jestjs.io/docs/en/asynchronous and https://jestjs.io/docs/en/tutorial-async
const fetch = require("node-fetch")
test('fetch', () => {
fetch("https://sites.google.com/unitn.it/seii-inf-org-unitn").then( (r) => {
expect(r.status).toEqual(200)
})
})
This does not work because fetch is a non-blocking call.
test('fetch', done => {
...
done()
}
api.js
:const express = require('express')
var bodyParser = require('body-parser')
const app = express()
app.use( bodyParser.json() )
app.use( bodyParser.urlencoded({ extended: true }) )
const PORT = process.env.PORT || 3000
var courses_offered = [{id: 21, name: 'IS2'}, {id: 28, name:'sweng'}]
app.get('/courses', (req, res) => {
res.json(courses_offered)
})
app.listen(PORT, () => console.log('App listening on port ' + PORT) )
client.js
:const fetch = require("node-fetch");
const url = "http://localhost:3000/"
async function get(url) {
console.log('getting ' + url)
const response = await fetch(url)
const json = await response.json()
console.log(json)
return json
}
get(url+'courses')
api.test.js
:const fetch = require("node-fetch");
const url = "http://localhost:3000/courses"
it('works with get', async () => {
expect.assertions(1)
var response = await fetch(url)
expect(response.status).toEqual(200)
})
Whitebox testing, and
Exercises:
For the below,
Given this function, achieve