温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

nodejs渐入佳境[20]-postman测试express+mogoDB项目

发布时间:2020-07-13 18:27:06 来源:网络 阅读:449 作者:jonson_jackson 栏目:开发技术

安装postman

网址:https://www.getpostman.com

网址访问,保存数据

postman.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var mongoose = require('mongoose');
var express = require('express');
var bodyParser = require('body-parser');

//app
var app = express();

//express middleware  Jonson对象与字符串转换。
app.use(bodyParser.json());

//
mongoose.Promise = global.Promise;
//连接mogodb
mongoose.connect('mongodb://localhost:27017/TodoApp');

//模版
var Todo = mongoose.model('Todo',{
   text:{
     type:String,  //类型
     required:true, //必须要有
     minlength:1, //最小长度
     trim:true   //去除空格
   },
   completed:{
     type:Boolean,
     default:false  //默认值
   },
   completedAt:{
     type:Number,
     default:null
   }
});

//express route
app.post('/todos',(req,res)=>{
//  console.log(req.body);

   //建立对象document
   var todo = new Todo({
       text:req.body.text
   });
   //保存
     todo.save().then((doc)=>{
     res.send(doc);
   },(e)=>{
       res.status(400).send(e);
   });

})
//监听
app.listen(3000,()=>{
   console.log('Start on port 3000');
});

module.exports = {
  app,
  Todo
}

测试

安装expect nodemon supertest mocha
//test/postman.test.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

const {app,Todo} = require('../postman')

const expect = require('expect')
const request = require('supertest')



beforeEach((done) => {
 Todo.remove({}).then(() => done());
});

describe('POST /todos', () => {
 it('should create a new todo', (done) => {
   var text = 'Test todo text';

   request(app)
     .post('/todos')
     .send({text})
     .expect(200)
     .expect((res) => {
       expect(res.body.text).toBe(text);
     })
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find().then((todos) => {
         expect(todos.length).toBe(1);
         expect(todos[0].text).toBe(text);
         done();
       }).catch((e) => done(e));
     });
 });

 it('should not create todo with invalid body data', (done) => {
   request(app)
     .post('/todos')
     .send({})
     .expect(400)
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find().then((todos) => {
         expect(todos.length).toBe(0);
         done();
       }).catch((e) => done(e));
     });
 });
});

修改package.json

1
2
3
4
"scripts": {
 "test": "mocha",
 "test-watch":"nodemon --exec 'npm test'",
}

运行

1
>npm run test-watch

获取所有document

1
2
3
4
5
6
7
app.get('/todos', (req, res) => {
 Todo.find().then((todos) => {
   res.send({todos});
 }, (e) => {
   res.status(400).send(e);
 })
});

测试2

//test/postman.test.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

const {app,Todo} = require('../postman')

const expect = require('expect')
const request = require('supertest')



const todos = [{
 text: 'First test todo'
}, {
 text: 'Second test todo'
}];

beforeEach((done) => {
 Todo.remove({}).then(() => {// 删除后插入对象
   return Todo.insertMany(todos);
 }).then(() => done());
});

describe('POST /todos', () => {
 it('should create a new todo', (done) => {
   var text = 'Test todo text';

   request(app)
     .post('/todos')
     .send({text})
     .expect(200)
     .expect((res) => {
       expect(res.body.text).toBe(text);
     })
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find({text}).then((todos) => {
         expect(todos.length).toBe(1);
         expect(todos[0].text).toBe(text);
         done();
       }).catch((e) => done(e));
     });
 });

 it('should not create todo with invalid body data', (done) => {
   request(app)
     .post('/todos')
     .send({})
     .expect(400)
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find().then((todos) => {
         expect(todos.length).toBe(2);
         done();
       }).catch((e) => done(e));
     });
 });
});

describe('GET /todos', () => {
 it('should get all todos', (done) => {
   request(app)
     .get('/todos')
     .expect(200)
     .expect((res) => {
       expect(res.body.todos.length).toBe(2);
     })
     .end(done);
 });
});

查询id

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//查询id
app.get('/todos/:id', (req, res) => {
 var id = req.params.id;

 if (!ObjectID.isValid(id)) {
   return res.status(404).send();
 }

 Todo.findById(id).then((todo) => {
   if (!todo) {
     return res.status(404).send();
   }

   res.send({todo});
 }).catch((e) => {
   res.status(400).send();
 });
});

测试3:

//test/postman.test.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102

const {app,Todo} = require('../postman')
const {ObjectID} = require('mongodb');
const expect = require('expect')
const request = require('supertest')


const todos = [{
 _id: new ObjectID(),
 text: 'First test todo'
}, {
 _id: new ObjectID(),
 text: 'Second test todo'
}];

beforeEach((done) => {
 Todo.remove({}).then(() => {
   return Todo.insertMany(todos);
 }).then(() => done());
});

describe('POST /todos', () => {
 it('should create a new todo', (done) => {
   var text = 'Test todo text';

   request(app)
     .post('/todos')
     .send({text})
     .expect(200)
     .expect((res) => {
       expect(res.body.text).toBe(text);
     })
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find({text}).then((todos) => {
         expect(todos.length).toBe(1);
         expect(todos[0].text).toBe(text);
         done();
       }).catch((e) => done(e));
     });
 });

 it('should not create todo with invalid body data', (done) => {
   request(app)
     .post('/todos')
     .send({})
     .expect(400)
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find().then((todos) => {
         expect(todos.length).toBe(2);
         done();
       }).catch((e) => done(e));
     });
 });
});

describe('GET /todos', () => {
 it('should get all todos', (done) => {
   request(app)
     .get('/todos')
     .expect(200)
     .expect((res) => {
       expect(res.body.todos.length).toBe(2);
     })
     .end(done);
 });
});

describe('GET /todos/:id', () => {
 it('should return todo doc', (done) => {
   request(app)
     .get(`/todos/${todos[0]._id.toHexString()}`)
     .expect(200)
     .expect((res) => {
       expect(res.body.todo.text).toBe(todos[0].text);
     })
     .end(done);
 });

 it('should return 404 if todo not found', (done) => {
   var hexId = new ObjectID().toHexString();

   request(app)
     .get(`/todos/${hexId}`)
     .expect(404)
     .end(done);
 });

 it('should return 404 for non-object ids', (done) => {
   request(app)
     .get('/todos/123abc')
     .expect(404)
     .end(done);
 });
});

删除id

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//删除
app.delete('/todos/:id', (req, res) => {
 var id = req.params.id;

 if (!ObjectID.isValid(id)) {
   return res.status(404).send();
 }

 Todo.findByIdAndRemove(id).then((todo) => {
   if (!todo) {
     return res.status(404).send();
   }

   res.send({todo});
 }).catch((e) => {
   res.status(400).send();
 });
});

测试4

//test/postman.test.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
const {app,Todo} = require('../postman')
const {ObjectID} = require('mongodb');
const expect = require('expect')
const request = require('supertest')


const todos = [{
 _id: new ObjectID(),
 text: 'First test todo'
}, {
 _id: new ObjectID(),
 text: 'Second test todo'
}];

beforeEach((done) => {
 Todo.remove({}).then(() => {
   return Todo.insertMany(todos);
 }).then(() => done());
});

describe('POST /todos', () => {
 it('should create a new todo', (done) => {
   var text = 'Test todo text';

   request(app)
     .post('/todos')
     .send({text})
     .expect(200)
     .expect((res) => {
       expect(res.body.text).toBe(text);
     })
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find({text}).then((todos) => {
         expect(todos.length).toBe(1);
         expect(todos[0].text).toBe(text);
         done();
       }).catch((e) => done(e));
     });
 });

 it('should not create todo with invalid body data', (done) => {
   request(app)
     .post('/todos')
     .send({})
     .expect(400)
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.find().then((todos) => {
         expect(todos.length).toBe(2);
         done();
       }).catch((e) => done(e));
     });
 });
});

describe('GET /todos', () => {
 it('should get all todos', (done) => {
   request(app)
     .get('/todos')
     .expect(200)
     .expect((res) => {
       expect(res.body.todos.length).toBe(2);
     })
     .end(done);
 });
});

describe('GET /todos/:id', () => {
 it('should return todo doc', (done) => {
   request(app)
     .get(`/todos/${todos[0]._id.toHexString()}`)
     .expect(200)
     .expect((res) => {
       expect(res.body.todo.text).toBe(todos[0].text);
     })
     .end(done);
 });

 it('should return 404 if todo not found', (done) => {
   var hexId = new ObjectID().toHexString();

   request(app)
     .get(`/todos/${hexId}`)
     .expect(404)
     .end(done);
 });

 it('should return 404 for non-object ids', (done) => {
   request(app)
     .get('/todos/123abc')
     .expect(404)
     .end(done);
 });
});

describe('DELETE /todos/:id', () => {
 it('should remove a todo', (done) => {
   var hexId = todos[1]._id.toHexString();

   request(app)
     .delete(`/todos/${hexId}`)
     .expect(200)
     .expect((res) => {
       expect(res.body.todo._id).toBe(hexId);
     })
     .end((err, res) => {
       if (err) {
         return done(err);
       }

       Todo.findById(hexId).then((todo) => {
         expect(todo).toBeFalsy();
         done();
       }).catch((e) => done(e));
     });
 });

 it('should return 404 if todo not found', (done) => {
   var hexId = new ObjectID().toHexString();

   request(app)
     .delete(`/todos/${hexId}`)
     .expect(404)
     .end(done);
 });

 it('should return 404 if object id is invalid', (done) => {
   request(app)
     .delete('/todos/123abc')
     .expect(404)
     .end(done);
 });
});

更新

1
> npm install --save lodash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//更新
app.patch('/todos/:id', (req, res) => {
 var id = req.params.id;
 var body = _.pick(req.body, ['text', 'completed']);

 if (!ObjectID.isValid(id)) {
   return res.status(404).send();
 }

 if (_.isBoolean(body.completed) && body.completed) {
   body.completedAt = new Date().getTime();
 } else {
   body.completed = false;
   body.completedAt = null;
 }

 Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
   if (!todo) {
     return res.status(404).send();
   }

   res.send({todo});
 }).catch((e) => {
   res.status(400).send();
 })
});

测试5

//test/postman.test.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
describe('PATCH /todos/:id', () => {
 it('should update the todo', (done) => {
   var hexId = todos[0]._id.toHexString();
   var text = 'This should be the new text';

   request(app)
     .patch(`/todos/${hexId}`)
     .send({
       completed: true,
       text
     })
     .expect(200)
     .expect((res) => {
       expect(res.body.todo.text).toBe(text);
       expect(res.body.todo.completed).toBe(true);
       expect(typeof res.body.todo.completedAt).toBe('number');
     })
     .end(done);
 });

 it('should clear completedAt when todo is not completed', (done) => {
   var hexId = todos[1]._id.toHexString();
   var text = 'This should be the new text!!';

   request(app)
     .patch(`/todos/${hexId}`)
     .send({
       completed: false,
       text
     })
     .expect(200)
     .expect((res) => {
       expect(res.body.todo.text).toBe(text);
       expect(res.body.todo.completed).toBe(false);
       expect(res.body.todo.completedAt).toBeFalsy();
     })
     .end(done);
 });
});
  • 本文链接: https://dreamerjonson.com/2018/11/18/node-20-postman/

  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!

nodejs渐入佳境[20]-postman测试express+mogoDB项目

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI