Add tests for stats api

This commit is contained in:
Michael Jackson 2019-07-10 13:24:27 -07:00
parent 56110b0314
commit ce9206f59e
5 changed files with 56 additions and 14 deletions

View File

@ -1,8 +1,9 @@
module.exports = {
moduleNameMapper: {
'entry-manifest': '<rootDir>/modules/__mocks__/entryManifest.js',
'\\.css$': '<rootDir>/modules/__mocks__/styleMock.js',
'\\.png$': '<rootDir>/modules/__mocks__/imageMock.js',
'\\.css$': '<rootDir>/modules/__mocks__/styleMock.js'
'entry-manifest': '<rootDir>/modules/__mocks__/entryManifest.js',
'getStats\\.js': '<rootDir>/modules/__mocks__/getStatsMock.js'
},
testMatch: ['**/__tests__/*-test.js'],
testURL: 'http://localhost/'

View File

@ -0,0 +1,29 @@
export default function getStats(since, until) {
const stats = {
since: since,
until: until,
requests: {
all: 0,
cached: 0,
country: 0,
status: 0
},
bandwidth: {
all: 0,
cached: 0,
country: 0
},
threats: {
all: 0,
country: 0
},
uniques: {
all: 0
}
};
return Promise.resolve({
timeseries: [stats],
totals: stats
});
}

View File

@ -0,0 +1,20 @@
import request from 'supertest';
import createServer from '../createServer.js';
describe('A request for stats', () => {
let server;
beforeEach(() => {
server = createServer();
});
it('returns a 200 JSON response', done => {
request(server)
.get('/api/stats')
.end((err, res) => {
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toMatch(/\bapplication\/json\b/);
done();
});
});
});

View File

@ -1,4 +1,4 @@
import { subDays, startOfDay, startOfSecond } from 'date-fns';
import { subDays, startOfDay } from 'date-fns';
import getStats from './utils/getStats.js';
@ -20,18 +20,10 @@ export default function serveStats(req, res) {
since = subDays(until, 30);
}
} else {
if (!req.query.since) {
return res.status(403).send({ error: 'Missing ?since query parameter' });
}
if (!req.query.until) {
return res.status(403).send({ error: 'Missing ?until query parameter' });
}
since = new Date(req.query.since);
until = req.query.until
? new Date(req.query.until)
: startOfSecond(new Date());
: startOfDay(new Date());
since = req.query.since ? new Date(req.query.since) : subDays(until, 1);
}
if (isNaN(since.getTime())) {

View File

@ -4,7 +4,7 @@ const cloudflareURL = 'https://api.cloudflare.com/client/v4';
const cloudflareEmail = process.env.CLOUDFLARE_EMAIL;
const cloudflareKey = process.env.CLOUDFLARE_KEY;
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
if (process.env.NODE_ENV !== 'production') {
if (!cloudflareEmail) {
throw new Error('Missing the $CLOUDFLARE_EMAIL environment variable');
}