qs.js
function parse(str) {
let arr = str.split('&');
let obj = {};
arr.forEach((item) => {
let [key, val] = item.split('=');
obj[key] = val;
});
return obj;
}
function stringify(obj) {
let arr = [];
for (let key in obj) {
arr.push(key + '=' + obj[key]);
}
return arr.join('&');
}
exports.parse = parse;
exports.stringify = stringify;
问题 | 解决方案 |
---|---|
污染 源代码里混杂了很多测试代码 | 从源代码中抽离出去 |
零散 杂乱无章,不能分组和分类 | 整体规划 和设计 |
没有持久化 没有存储 | 把测试文件单独存放 |
手动跑测试比较麻烦 | 自动运行并显示结果 |
Test-Driven-Development
测试驱动开发,
cnpm i jest --save-dev
cnpm i jest -g
**test.js
jest npm jest
npm test
qs.test.js
let { parse, stringify } = require('./qs');
describe('parse', () => {//分组
test('one', () => {//测试用例
expect(parse("name=zfpx").name).toBe('zfpx');
});
test('two', () => {
expect(parse("name=zfpx&age=9").age).toBe('9');
});
});
describe('stringify', () => {
test('one', () => {
expect(stringify({ name: 'zfpx' })).toBe('name=zfpx');
});
test('two', () => {
expect(stringify({ name: 'zfpx', age: 9 })).toBe('name=zfpx&age=9');
});
});
module.exports = {
testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)(spec|test).js?(x)'],//设置识别哪些文件是测试文件(glob形式),与testRegex互斥,不能同时写
testRegex: '(/__tests__).*|(\\.|/)(test|spec))\\.jsx?$',//设置识别哪些文件是测试文件(正则形式),与testMatch互斥,不能同时写
testEnvironment: 'jsdom',//测试环境,默认值是:jsdom,可修改为node
rootDir: '',//默认值:当前目录,一般是package.json所在的目录。
moduleFileExtensions: ['js', 'json', 'jsx', 'node']//测试文件的类型
}
test('matchers', () => {
const a = {
name: 'a',
home: {
name: 'beijing'
}
}
const b = {
name: 'a',
home: {
name: 'beijing'
}
}
expect(a).toEqual(b)
expect([1, 2, 3]).toEqual([1, 2, 3])
expect(null).toBeNull()
expect([1, 2, 3]).toContain(1)
expect(b).toHaveProperty('home')
expect('abc').toContain('b')
expect('abc').toMatch(/^\w+$/)
expect('123').not.toContain('4')
})
function remove(node) {
node.parentNode.removeChild(node);
}
function on(node, type, handler) {
node.addEventListener(type, handler);
}
exports.remove = remove;
exports.on = on;
let { remove, on } = require('../src/dom');
describe('dom', () => {
test('remove', () => {
document.body.innerHTML = '<div id="container"><span id="hello">hello</span></div>';
let container = document.getElementById('container');
expect(container.nodeName.toLocaleLowerCase()).toBe('div');
let hello = document.getElementById('hello');
expect(hello.nodeName.toLocaleLowerCase()).toBe('span');
remove(hello);
let hello2 = document.getElementById('hello');
expect(hello2).toBeNull();
})
test('on', () => {
document.body.innerHTML = '<div id="container"><button id="clickMe">click</button></div>';
let clickMe = document.getElementById('clickMe');
on(clickMe, 'click', () => {
clickMe.innerHTML = 'clicked';
});
clickMe.click();
expect(clickMe.innerHTML).toBe('clicked');
})
});
<div id="tab">
<div>
<a href="#" class="tab-button">选项1</a>
<a href="#" class="tab-button">选项2</a>
</div>
<div>
<div class="tab-panel">面板1</div>
<div class="tab-panel">面板2</div>
</div>
</div>
class Tab{
constructor(id,buttonClass,panelClass){
this.tab = tab = document.querySelector('#'+id);
this.buttons = Array.from(tab.querySelectorAll('.'+buttonClass));
this.panels = Array.from(tab.querySelectorAll('.'+panelClass));
this.select(0);
this.bindEvent();
}
select(index){
this.buttons.forEach(button=>button.style.backgroundColor= 'white');
this.buttons[index].style.backgroundColor= 'red';
this.panels.forEach(panel=>panel.style.display= 'none');
this.panels[index].style.display= 'block';
}
bindEvent(){
for(let i=0;i<this.buttons.length;i++){
this.buttons[i].addEventListener('click',()=>{
this.select(i);
});
}
}
}
module.exports = Tab;
const Tab = require('../src/tab');
const fs = require('fs');
const path = require('path');
test('tab',function(){
document.body.innerHTML = fs.readFileSync(path.resolve(__dirname,'tab.html'),'utf8');
const tab = new Tab('tab','tab-button','tab-panel');
expect(tab.buttons[0].style.backgroundColor).toBe('red');
expect(tab.buttons[1].style.backgroundColor).toBe('white');
expect(tab.panels[0].style.display).toBe('block');
expect(tab.panels[1].style.display).toBe('none');
tab.buttons[1].click();
expect(tab.buttons[0].style.backgroundColor).toBe('white');
expect(tab.buttons[1].style.backgroundColor).toBe('red');
expect(tab.panels[0].style.display).toBe('none');
expect(tab.panels[1].style.display).toBe('block');
});
test('async',(done)=>{
setTimeout(()=>{
expect(2).toBe(2);
done();
},1000);
});
__tests__\users.js
jest.mock('../js/ajax');
const getUsers = require('../js/getUsers');
test('getUsers',(done)=>{
document.body.innerHTML = `<ul id="users"></ul>`;
getUsers('/users.json','users',()=>{
const ul = document.querySelector('#users');
const lis = ul.querySelectorAll('li');
expect(lis.length).toBe(2);
expect(lis[1].innerHTML).toBe('zfpx2');
done();
});
});
\js\getUsers.js
var ajax = require('./ajax');
function getUsers(url,id,callback){
const users = document.getElementById(id);
ajax(url,data=>{
console.log('ajax ok');
data = JSON.parse(data);
users.innerHTML = data.map(item=>`<li>${item.name}</li>`).join('');
callback&&callback();
});
}
module.exports = getUsers;
\js\ajax.js
function ajax(url,success){
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = ()=>{
if(xhr.readyState == 4){
success&success(xhr.responseText);
}
}
xhr.open('get',url);
xhr.send(null);
}
module.exports = ajax;
js__mocks__\ajax.js
const fs = require('fs');
const path = require('path');
const ajax = (url,success)=>{
setTimeout(()=>{
success(JSON.stringify([{name:'zfpx1'},{name:'zfpx2'}]));
},1000);
}
module.exports = ajax;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul id="users"></ul>
<script>
let module = {};
let require = () => ajax;
</script>
<script src="/js/ajax.js"></script>
<script src="/js/getUsers.js"></script>
<script>
getUsers('http://localhost:3000/users.json', 'users');
</script>
</body>
</html>
users.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul id="users"></ul>
<script>
let module = {};
let require = () => ajax;
</script>
<script src="/js/ajax.js"></script>
<script src="/js/getUsers.js"></script>
<script>
getUsers('http://localhost:3000/users.json', 'users');
</script>
</body>
</html>
server.js
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(__dirname));
app.get('/',function(req,res){
res.sendFile(path.resolve(__dirname,'users.html'));
});
app.get('/users.json',function(req,res){
res.json([{name:'zfpx1'},{name:'zfpx2'}]);
});
app.listen(3000);
npx jest --coverage
gulp内部使用了node-glob模块来实现其文件匹配功能。我们可以使用下面这些特殊的字符来匹配我们想要的文件:
匹配符 | 说明 |
---|---|
星 | 匹配文件路径中的0个或多个字符,但不会匹配路径分隔符 |
** | 匹配路径中的0个或多个目录及其子目录 |
[...] | 匹配方括号中出现的字符中的任意一个,当方括号中第一个字符为^或!时,则表示不匹配方括号中出现的其他字符中的任意一个 |
!(pattern pattern pattern) | 匹配任何与括号中给定的任一模式都不匹配的 |
?(pattern pattern pattern) | 匹配括号中给定的任一模式0次或1次,类似于js正则中的? |
+(pattern pattern pattern) | 匹配括号中给定的任一模式至少1次,类似于js正则中的+ |
(pattern pattern pattern) | 匹配括号中给定的任一模式0次或多次,类似于js正则中的 * |
@(pattern pattern pattern) | 匹配括号中给定的任一模式1次,类似于js正则中的 |
glob | 匹配 | |
---|---|---|
* | 能匹配 a.js,x.y,abc,abc/,但不能匹配a/b.js | |
. | a.js,style.css,a.b,x.y | |
//*.js | 能匹配 a/b/c.js,x/y/z.js,不能匹配a/b.js,a/b/c/d.js | |
** | 能匹配 abc,a/b.js,a/b/c.js,x/y/z,x/y/z/a.b,能用来匹配所有的目录和文件 | |
a/**/z | 能匹配 a/z,a/b/z,a/b/c/z,a/d/g/h/j/k/z | |
a/**b/z | 能匹配 a/b/z,a/sb/z,但不能匹配a/x/sb/z,因为只有单**单独出现才能匹配多级目录 | |
?.js | 能匹配 a.js,b.js,c.js | |
a?? | 能匹配 a.b,abc,但不能匹配ab/,因为它不会匹配路径分隔符 | |
[xyz].js | 只能匹配 x.js,y.js,z.js,不会匹配xy.js,xyz.js等,整个中括号只代表一个字符 | |
[^xyz].js | 能匹配 a.js,b.js,c.js等,不能匹配x.js,y.js,z.js |