This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging
Recently, I just took over a multi-project of Angular1.3 front-end + Node server side. As a beginner of node, I wrote unit test cases for the existing interface after getting familiar with node code. This blog is for simple record.
Mocha is introduced
Mocha is one of the most popular JavaScript testing frameworks available in both browsers and Node environments.
The installation
npm i mocha -g
Copy the code
Simple test script
1. First write a simple example, add.js
function add(a, b){
return a+b;
}
module.exports = add;
Copy the code
2. Create a test script add.test.js. Generally, the test script has the same name as the original script, but the suffix is.test.js
let calcu = require('./add');
let should = require("should");
describe("add func test".() = > {
it('2 add 2 should equal 4'.() = > {
calcu.add(2.2).should.equal(4)})})Copy the code
3. Execute the test case
mocha demo1/mocha demo1/calcu.test.js
Copy the code
Describe refers to a test suite, which is a test of a sequence of related programs. It refers to a unit test, which is the smallest unit of testing.
Assertions library
The assertion library can be understood as comparing functions, that is, whether an assertion function is consistent with expectations. If it is consistent, the test passes. If it is not consistent, the test fails. Mocha itself does not contain assertion libraries, so it is necessary to introduce third-party assertion libraries. At present, the more popular assertion libraries are should.js, expect. Here is an example of the should assertion:
===.exactly(5).should.be.exactly(5).ok true.should.be.ok; 'yay'.should.be.ok; (1).should.be.ok; ({}).should.be.ok; false.should.not.be.ok; / / true. True (5 = = = 5). Should be. True (err = = = null). Should be. True; / / equal, equivalent to = = eql ({foo: 'bar'}). Should the eql ({foo: 'bar'}); [1, 2, 3]. Should. Eql ([1, 2, 3]); // see next example it is correct, even if it is different types, but actual content the same [1, 2, 3].should.eql({ '0': 1, '1': 2, '2': 3 }); // undefined number.NaN (undefined + 0).should.be.NaN; Typeof user.should.be.type('object'); 'test'.should.be.type('string'); / / a instance constructor. Instanceof user.. Should be. The an. Instanceof (user); [].should.be.an.instanceOf(Array); . / / there exist () should not. Exist (err) / / depth contains containDeep () [[1], [2], [3]]. Should the containDeep ([[3]]); [[1],[2],[3, 4]].should.containDeep([[3]]); [{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{a: 'a'}]); [{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{b: 'b'}]); .throw() and throwError() (function(){throw new Error('fail'); }).should.throw(); (function(){ throw new Error('fail'); }).should.throw('fail'); // The header of the HTTP response contains.header res.should.have. Header ('content-length'); res.should.have.header('Content-Length', '123'); // Contains or equivalent to.containeql ({b: 10}).should.containeQL ({b: 10}); // contains or equivalent to.containeql ({b: 10}).should.containeQL ({b: 10}); ([1, 2, { a: 10 }]).should.containEql({ a: 10 });Copy the code
usage
General function test
Add.test.js as shown above
Asynchronous function testing
Create a new file, book.js
let fs = require('fs');
exports.read = (cb) = > {
fs.readFile('./book.txt'.'utf-8'.(err, result) = > {
if (err) return cb(err);
console.log("result",result);
cb(null, result); })}Copy the code
Create a new file, book.test.js
let book = require('./book');
let expect = require("chai").expect;
let book = require('./book');
let expect = require("chai").expect;
describe("async".() = > {
it('read book async'.function (done) {
book.read((err, result) = > {
expect(err).equal(null);
expect(result).to.be.a('string'); done(); })})})Copy the code
Run mocha book.test.js and we’ll see that it’s successful, but if we add a timing function to book.js, we’ll see the following example:
let fs = require('fs');
exports.read = (cb) = > {
setTimeout(function() {
fs.readFile('./book.txt'.'utf-8'.(err, result) = > {
if (err) return cb(err);
console.log("result",result);
cb(null, result); })},3000);
}
Copy the code
The following error will be reported:
Timeout of 2000ms exceeded.
Copy the code
This is because Mocha defaults to performing a maximum of 2000 milliseconds per test case and reports an error if no results are available by then. Therefore, we need to specify an extra timeout time for asynchronous operations.
mocha --timeout 5000 book.test.js
Copy the code
This ensures the success of the test case.
The API test
Using Mocha and should alone can satisfy unit tests of almost any JavaScript function. But for Node applications, it’s more than just a collection of functions, such as testing a Web application. You need to work with an HTTP proxy to test HTTP requests and routes. Supertest is an HTTP proxy service engine that simulates all HTTP request behavior. Supertest can be used with any application framework to unit test an application. 1. Install supertest NPM I supertest –save-dev 2. Pass in the application to instantiate the supertest
let app = new koa();
let server = app.listen(0);
this.request = supertest(server);
Copy the code
3. Call the API for testing
//get
describe('GET /users'.function(){
it('respond with json'.function(done){
request(app)
.get('/user')
.set('Accept'.'application/json')
.expect(200)
.end(function(err, res){
should.not.exist(err);
res.text.should.containEql('success');
done();
});
});
});
//post
describe('test login'.function(){
it('login sucessfully'.function (done) {
request.post('/user')
.send({ username: 'username'.password: '123456' })
.end(function (err, res) {
should.not.exists(err);
done();
});
});
})
Copy the code
Alternatively, you can test file uploads with the.attach() method.
Common Command Lines
node ./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha
open coverage/lcov-report/index.html
Copy the code
Life is a hook
Mocha has four life hooks
- Before () : Execute before all test cases for this block
- After () : Executes after all test cases for the block
- BeforeEach () : executed beforeEach unit test
- AfterEach () : executed afterEach unit test