我目前正在从事商业审查申请项目。我需要创建一个函数来处理基于位置或类别的过滤业务(我目前使用的是虚拟数据)。我已经成功地添加了按位置过滤。 Istanbul 尔测试报告说我在我的一个函数中发现了一行(弄乱了我拥有 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();
});
});
});
});
还有一张我在纽约 Istanbul 尔报道的照片:
如何只测试这条未覆盖的线?
最佳答案
该行测试 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();
});
});
但是您的源代码对于这种情况有点低效。它仍然对业务进行无意义的迭代。也许你应该在 if (location)
子句中添加一个 else
并返回一个 400
响应代码,因为这确实是一个请求问题。
关于javascript - 我可以测试函数中的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49862902/