使用 express,我應該撰寫一個從提供的 JSON 檔案中獲取跟蹤資訊的應用程式:
- 獲取所有曲目
- 通過 id 獲取特定曲目
- 獲取按曲目名稱或持續時間排序的曲目串列(取決于 sortBy 查詢字串引數)
當我使用 Postman 擺弄它時,該應用程式運行良好,但是當使用 Jest 和 Supertest 撰寫測驗時,它們都失敗了。
應用程式
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const tracksRouter = require('./routes/routes-tracks');
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/tracks', tracksRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.send(err.message);
});
module.exports = app;
路線
const express = require('express');
const router = express.Router();
const tracks = require('../controllers/controller');
router.get('/sorted', function (req, res) {
try {
const result = tracks.getSorted(req.query.sortBy);
res.status(200).send(result);
res.end();
} catch (error) {
res.status(500).send(error);
res.end();
}
});
router.get('/:id', function (req, res) {
try {
const result = tracks.getById(req.params.id);
res.status(200).send(result);
res.end();
} catch (error) {
res.status(500).send(error);
res.end();
}
});
router.get('/', function (req, res) {
try {
const result = tracks.getAll();
res.status(200).send(result);
res.end();
} catch (error) {
res.status(500).send(error);
res.end();
}
});
module.exports = router;
路線測驗
const app = require('../../app');
const request = require('supertest');
describe('GET /tracks', () => {
it('GET /tracks/sorted?sortBy=duration should return array of tracks sorted by duration', () => {
const res = request(app).get('/tracks/sorted?sortBy=duration');
expect(res.statusCode).toEqual(200);
expect(res.body[0].id).toEqual(ID_EDITED);
});
it('GET /tracks/sorted?sortBy=name should return array of tracks sorted by name', () => {
const res = request(app).get('/tracks/sorted?sortBy=name');
expect(res.statusCode).toEqual(200);
expect(res.body[0].artist.name).toEqual(ARTIST_EDITED);
});
it('GET /tracks:id should return track with given id', () => {
const res = request(app).get('/tracks/ID_EDITED');
expect(res.statusCode).toEqual(200);
expect(res.body.id).toEqual(ID_EDITED);
expect(res.body.title).toEqual(SONGNAME_EDITED);
});
it('GET /tracks should return an array of all tracks', () => {
const res = request(app).get('/tracks');
expect(res.statusCode).toEqual(200);
expect(res.body[0]).toHaveProperty('duration');
});
});
控制器
const database = require('../tools/db-import');
const trackList = database.getTrackList();
function getAll() {
try {
return trackList;
} catch (error) {
return error;
}
}
function getById(trackId) {
try {
return trackList.find((item) => item.id == trackId);
} catch (error) {
return error;
}
}
function getSorted(sortParameter) {
try {
if (sortParameter == 'duration') {
return trackList.sort((a, b) => (a.duration > b.duration) ? 1 : -1);
} else if (sortParameter == 'name') {
return trackList.sort((a, b) => (a.artist.name > b.artist.name) ? 1 : -1);
}
else {
return 'Wrong input.'
}
} catch (error) {
return error;
}
}
module.exports.getAll = getAll;
module.exports.getById = getById;
module.exports.getSorted = getSorted;
模型
const tracks = require('../models/tracks');
function getAll() {
try {
return tracks.getAll();
} catch (error) {
return error;
}
}
function getById(id) {
try {
return tracks.getById(id);
} catch (error) {
return error;
}
}
function getSorted(sortParameter) {
try {
return tracks.getSorted(sortParameter);
} catch (error) {
return error;
}
}
module.exports.getAll = getAll;
module.exports.getById = getById;
module.exports.getSorted = getSorted;
資料庫匯入
const data = require('../database/JSON_EDITED.json');
function getTrackList() {
return data.tracks.data;
}
module.exports.getTrackList = getTrackList;
開玩笑的失敗資訊示例:
expect(received).toEqual(expected) // deep equality
Expected: 200
Received: undefined
8 | const res = request(app).get('/tracks/sorted?sortBy=duration');
9 |
> 10 | expect(res.statusCode).toEqual(200);
| ^
11 | expect(res.body[0].id).toEqual(ID_EDITED);
12 | });
13 |
at Object.<anonymous> (routes/__test__/routes-tracks.test.js:10:32)
uj5u.com熱心網友回復:
如果您查看 supertest檔案,您可以看到該request函式是異步的并回傳一個 Promise。
它們提供不同的語法,但我個人會使用async/await一種:
it('GET /tracks/sorted?sortBy=duration should return array of tracks sorted by duration', async () => {
const res = await request(app).get('/tracks/sorted?sortBy=duration');
expect(res.statusCode).toEqual(200);
expect(res.body[0].id).toEqual(ID_EDITED);
});
但你也可以使用then回呼:
it('GET /tracks/sorted?sortBy=duration should return array of tracks sorted by duration', () => {
return request(app)
.get('/tracks/sorted?sortBy=duration')
.then((res) => {
expect(res.statusCode).toEqual(200);
expect(res.body[0].id).toEqual(ID_EDITED);
});
});
最后,您可以使用 Jest 的異步匹配器(不適合此用例,此處僅進行部分檢查):
it('GET /tracks/sorted?sortBy=duration should return array of tracks sorted by duration', () => {
expect(request(app).get('/tracks/sorted?sortBy=duration')).resolves.toHaveProperty('statusCode', 200);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/435003.html
標籤:javascript 节点.js 表示 开玩笑的
上一篇:NodeJs:有沒有辦法退出整個函式,而不僅僅是回傳內部函式?
下一篇:如果字串包含文本,我如何創建
