我有一个这样的控制器/路由文件..
const express = require('express');
const pService = require('../../services/parameter/service');
let router = express.Router()
router.get('/valuebyobject/:main/:sub?', pService.getValue);
getValue 函数如下所示..
const getValue = async (req, res, next) => {
try {
let ts = Date.now();
const obj= {};
obj.utime = ts;
obj.data =[];
const valueMain = req.params.main;
const sub = req.params.sub;
var jsonPath = path.join(__dirname, '..','..', 'data','Format_'+valueMain+'.json');
fs.readFile(jsonPath, (err, data) => {
if (err) return res.status(404).json({
'code': 'NOT_FOUND',
'description': `Required Main Parameter: ${valueMain} result is empty`
});
let file = JSON.parse(data);
if(sub){ //If 'sub' param is not empty, take both 'main' and 'sub'
const filterData = file['Data'].filter(element=>{
if (element.Id == sub) //Filtering according to Main & Sub params
obj.data.push({'My': parseInt(valueMain), 'Other': parseInt(element.Id), 'Value': element.Value})
return element;
})
if(typeof filterData != "undefined" && filterData != null && filterData.length != null && filterData.length > 0) //Checking if array is not empty
{
console.log(obj)
res.send(obj);
}
else { // If array is empty send 404 back
return res.status(404).json({
'code': 'NOT_FOUND',
'description': `Required Sub Parameter ${sub} result is empty`
});
}
}
else { // if 'sub' parameter is empty then query with only 'main' param
const filterData = file['Data'].filter(element=>{
obj.data.push({'My': parseInt(valueMain), 'Other': parseInt(element.Id), 'Value': element.Value})
return element;
})
if(typeof filterData != "undefined" && filterData != null && filterData.length != null && filterData.length > 0) //Checking if array is not empty
{
console.log(obj)
res.send(obj);
}
else { // If array is empty send 404 back
return res.status(404).json({
'code': 'NOT_FOUND',
'description': `Required Sub Parameter ${sub} result is empty`
});
}
}
});
} catch (err) {
return res.status(500).json({
'code': 'SERVER_ERROR',
'description': 'something went wrong, Please try again'
});
}
}
我正在用 chai 测试以下路线,我有一个如下所示的测试文件..
const chai = require("chai");
const chaiHttp = require("chai-http");
const expect = chai.expect;
const server = require("../controllers/apis/parameter");
chai.should();
chai.use(chaiHttp);
let main= 101
describe('Parameter APIs', () => {
describe('Test GET route (/valuebyobject', () => {
it('should return all ibjects', async () => {
let res = await chai
.request(server)
.get(`/valuebyobject/${main}`)
expect(res.status).to.equal(200)
});
});
});
通过运行测试文件,它给了我这个错误:
但我无法弄清楚如何使用 chai 测试我的 API 并避免此 TypeError 的解决方案。
但是从上面的控制器文件中将 express.Router() 更改为普通的 express() 使其工作。
const express = require('express');
const pService = require('../../services/parameter/service');
let router = express()
router.use(express.json())
router.get('/valuebyobject/:main/:sub?', pService.getValue);
但我想在我的应用程序中使用 expres.Router()。有人可以帮忙测试 express.Router() 的端点吗?