我目前正在开展业务审核应用项目。我需要创建一个函数来处理基于位置或类别的过滤业务(我目前正在使用虚拟数据)。我已经成功地按位置添加了过滤。伊斯坦布尔的测试报告说我在我的一个功能中发现了一条线(弄乱了我100%覆盖的光芒)。这是过滤功能。
import Models from '../models/Models';
import SendResponse from '../SendResponse';
const { Businesses } = Models;
const Filter = (req, res) => {
const { location, category } = req.query;
const theBusinesses = [];
let theQuery;
if (location) { //this line remains uncovered
theQuery = location;
}
Businesses.forEach((business) => {
if (business.state === theQuery) {
theBusinesses.push(business);
}
});
if (theBusinesses.length === 0) {
return SendResponse(res, 404, `There are currently no businesses in ${theQuery}`);
}
return SendResponse(res, 200, `Found ${theBusinesses.length} businesses`, theBusinesses);
};
export default Filter;
以下是我为过滤功能编写的测试:
describe('FILTER BY LOCATION TESTS', () => {
describe('When a user sends a GET request to /api/v1/businesses?<location>', () => {
it('Response message should equal "Found 1 businesses"', (done) => {
chai.request(app)
.get('/api/v1/businesses?location=Lagos')
.end((req, res) => {
assert.equal(res.body.message, 'Found 1 businesses');
done();
});
});
it('It should return 1 business', (done) => {
chai.request(app)
.get('/api/v1/businesses?location=Lagos')
.end((req, res) => {
res.body.responseObject.length.should.equal(1);
done();
});
});
it('It should return a 404 status', (done) => {
chai.request(app)
.get('/api/v1/businesses?location=Enugu')
.end((req, res) => {
res.should.have.status(404);
done();
});
});
});
});
和我的纽约伊斯坦布尔报告的照片:
如何测试这条未覆盖的线?
答案 0 :(得分:2)
该行测试location是否有值。由于您始终在所有测试用例中传递位置,因此不会覆盖/测试条件的其他分支路径,即位置为空的位置。
因此,尝试一个测试用例,调用API而不传递位置参数值。
it('It should return a 404 status when location is not provided', (done) => {
chai.request(app)
.get('/api/v1/businesses?location=')
.end((req, res) => {
res.should.have.status(404);
done();
});
});
但是您的源代码对于这种情况来说效率有点低。它仍然对企业进行无意义的迭代。也许您应该在else
子句中添加if (location)
并返回400
响应代码,因为这确实是一个请求问题。