不一定。可以采用测试驱动开发(TDD)的方法,由开发人员编写必要的单元测试,而功能和集成测试可以由专门的测试人员编写。下面的代码示例演示了如何在Node.js中使用Mocha和Chai库进行单元测试:
安装依赖:
npm install --save-dev mocha chai
book.js文件:
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
getTitle() {
return this.title;
}
getAuthor() {
return this.author;
}
}
module.exports = Book;
book.test.js文件:
const expect = require('chai').expect;
const Book = require('./book');
describe('Book', () => {
describe('#getTitle', () => {
it('should return the title of the book', () => {
const book = new Book('The Catcher in the Rye', 'J.D. Salinger');
expect(book.getTitle()).to.equal('The Catcher in the Rye');
});
});
describe('#getAuthor', () => {
it('should return the author of the book', () => {
const book = new Book('The Catcher in the Rye', 'J.D. Salinger');
expect(book.getAuthor()).to.equal('J.D. Salinger');
});
});
});
在控制台中输入以下命令运行测试:
./node_modules/mocha/bin/mocha
输出:
Book
#getTitle
✓ should return the title of the book
#getAuthor
✓ should return the author of the book
2 passing (9ms)
下一篇:API中的图像不显示