时间:2021-11-25 这几天项目来了,白天工作晚上就挺无聊的,每天都是半夜两三点了一点睡意没有,要熬到天亮了才困,再睡三个小时去上班,半夜打游戏,刷剧,做饭,能干的都干了,略感无聊,干多了就很没意思,想着这份前端工作也做几个月了,就想着学点测试和后端的内容


单元测试

Mocha 和 Chai 是两个通常一起用于单元测试的 JavaScript 框架。
可以测试方法的返回数据是否为期望
主要关键字为
describe - 方法名
It - 期望返回值

具体用法:

  1. function getContentType(filename) {
  2. const extension = filename.match(/.*\.([^\.]*)$/)[1];
  3. switch (extension) {
  4. case 'html':
  5. return 'text/html'
  6. case 'css':
  7. return 'text/css'
  8. case 'jpeg':
  9. return 'image/jpeg'
  10. case 'jpg':
  11. return 'image/jpeg'
  12. default:
  13. return 'text/plain'
  14. }
  15. }
  1. var fs = require('fs');
  2. var vm = require('vm');
  3. var path = 'js/request-logic.js';
  4. var code = fs.readFileSync(path);
  5. vm.runInThisContext(code);
  6. var should = require('chai').should();
  7. describe('getContentType()', function() {
  8. it('a function called getContentType should exist', function() {
  9. should.equal(typeof getContentType, 'function');
  10. });
  11. it('should return "text/html" for filenames ending in .html', function() {
  12. should.equal(getContentType('index.html'), 'text/html');
  13. });
  14. it('should return "text/css" for filenames ending in .css', function() {
  15. should.equal(getContentType('style.css'), 'text/css');
  16. });
  17. it('should return "image/jpeg" for filenames ending in .jpeg', function() {
  18. should.equal(getContentType('image.jpeg'), 'image/jpeg');
  19. });
  20. it('should return "image/jpeg" for filenames ending in .jpg', function() {
  21. should.equal(getContentType('image.jpg'), 'image/jpeg');
  22. });
  23. it('should return "text/plain" for all other file extensions', function() {
  24. should.equal(getContentType('image.unknown'), 'text/plain');
  25. });
  26. });

image.png