Skip to content

Commit

Permalink
add log statements
Browse files Browse the repository at this point in the history
  • Loading branch information
evelyn-lo committed Jan 23, 2025
1 parent 6bbbb3a commit 428ff59
Show file tree
Hide file tree
Showing 2 changed files with 192 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/posts/votes.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,29 @@ module.exports = function (Posts) {
if (isPrivileged) {
return;
}
if (reputation < meta.config[`min:rep:${type}`]) {
throw new Error(`[[error:not-enough-reputation-to-${type}, ${meta.config[`min:rep:${type}`]}]]`);

console.log('Reputation:', reputation);
const minReputationRequired = meta.config[`min:rep:${type}`];
console.log('Min Reputation Required:', minReputationRequired);
const errorMessage = `[[error:not-enough-reputation-to-${type}, ${minReputationRequired}]]`;
console.log('Error Message:', errorMessage);

if (reputation < minReputationRequired) {
console.log('here');
throw new Error(errorMessage);
}

Check failure on line 167 in src/posts/votes.js

View workflow job for this annotation

GitHub Actions / test

Trailing spaces not allowed
console.log('**Evelyn**');
console.log('Voted PIDs Today:', votedPidsToday);
console.log('Votes Today Limit:', votesToday);

Check failure on line 170 in src/posts/votes.js

View workflow job for this annotation

GitHub Actions / test

'votesToday' was used before it was defined
console.log('Voter Per User Today:', voterPerUserToday);

Check failure on line 171 in src/posts/votes.js

View workflow job for this annotation

GitHub Actions / test

'voterPerUserToday' was used before it was defined
console.log('Target UID:', targetUid);

Check failure on line 173 in src/posts/votes.js

View workflow job for this annotation

GitHub Actions / test

Trailing spaces not allowed

/*
if (reputation < meta.config[`min:rep:${type}`]) {
throw new Error(`[[error:not-enough-reputation-to-${type}, ${meta.config[`min:rep:${type}`]}]]`);
} */
const votesToday = meta.config[`${type}sPerDay`];
if (votesToday && votedPidsToday.length >= votesToday) {
throw new Error(`[[error:too-many-${type}s-today, ${votesToday}]]`);
Expand Down
170 changes: 170 additions & 0 deletions test/modules/api.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// Import the functions to be tested
import * as api from '../../public/src/modules/api';
import { fire as fireHook } from 'hooks';
import { confirm } from 'bootbox';

// Mock dependencies
jest.mock('hooks', () => ({
fire: jest.fn(),
}));
jest.mock('bootbox', () => ({
confirm: jest.fn(),
}));
global.fetch = jest.fn();

// Mock config
global.config = {
relative_path: '/test-path',
csrf_token: 'test-csrf-token',
};

// Test suite
describe('api.js', () => {
beforeEach(() => {
jest.clearAllMocks();
});

describe('call', () => {
it('should call xhr with correct options and return result', async () => {
const mockResponse = { response: { data: 'test' }, status: { message: 'Success' } };
global.fetch.mockResolvedValue({
ok: true,
json: async () => mockResponse,
headers: {
get: () => 'application/json',
},
});
fireHook.mockResolvedValue({ url: 'test-login' });

const result = await api.get('/test-route', { key: 'value' });
expect(result).toEqual({ data: 'test' });
expect(global.fetch).toHaveBeenCalledWith(
'/test-path/api/v3/test-route?key=value',
expect.objectContaining({
method: 'GET',
})
);
});

it('should handle reauthentication error', async () => {
const error = new Error('A valid login session was not found. Please log in and try again.');
global.fetch.mockRejectedValue(error);

fireHook.mockResolvedValue({ url: 'login' });
confirm.mockImplementation((_, cb) => cb(true));

try {
await api.get('/test-route');
} catch (err) {
expect(err).toBe(error);
}
expect(confirm).toHaveBeenCalledWith('[[error:api.reauth-required]]', expect.any(Function));
});

it('should throw an error for non-reauthentication issues', async () => {
const error = new Error('Test Error');
global.fetch.mockRejectedValue(error);

await expect(api.get('/test-route')).rejects.toThrow('Test Error');
});
});

describe('xhr', () => {
it('should handle JSON responses correctly', async () => {
const mockResponse = { response: { data: 'test' }, status: { message: 'Success' } };
global.fetch.mockResolvedValue({
ok: true,
json: async () => mockResponse,
headers: {
get: () => 'application/json',
},
});

const result = await api.get('/test-route');
expect(result).toEqual({ data: 'test' });
});

it('should handle non-JSON responses correctly', async () => {
global.fetch.mockResolvedValue({
ok: true,
text: async () => 'test-response',
headers: {
get: () => 'text/plain',
},
});

const result = await api.get('/test-route');
expect(result).toEqual('test-response');
});

it('should throw an error for non-OK responses', async () => {
global.fetch.mockResolvedValue({
ok: false,
statusText: 'Test Error',
headers: {
get: () => 'text/plain',
},
});

await expect(api.get('/test-route')).rejects.toThrow('Test Error');
});
});

describe('HTTP methods', () => {
it('should make GET requests correctly', async () => {
global.fetch.mockResolvedValue({
ok: true,
json: async () => ({}),
headers: {
get: () => 'application/json',
},
});

await api.get('/test-route', { key: 'value' });
expect(global.fetch).toHaveBeenCalledWith(
'/test-path/api/v3/test-route?key=value',
expect.objectContaining({ method: 'GET' })
);
});

it('should make POST requests correctly', async () => {
global.fetch.mockResolvedValue({
ok: true,
json: async () => ({}),
headers: {
get: () => 'application/json',
},
});

await api.post('/test-route', { key: 'value' });
expect(global.fetch).toHaveBeenCalledWith(
'/test-path/api/v3/test-route',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ key: 'value' }),
headers: expect.objectContaining({ 'x-csrf-token': 'test-csrf-token' }),
})
);
});

it('should make DELETE requests correctly', async () => {
global.fetch.mockResolvedValue({
ok: true,
json: async () => ({}),
headers: {
get: () => 'application/json',
},
});

await api.del('/test-route', { key: 'value' });
expect(global.fetch).toHaveBeenCalledWith(
'/test-path/api/v3/test-route',
expect.objectContaining({
method: 'DELETE',
body: JSON.stringify({ key: 'value' }),
headers: expect.objectContaining({ 'x-csrf-token': 'test-csrf-token' }),
})
);
});
});
});

0 comments on commit 428ff59

Please sign in to comment.