-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathurlShortener.ts
107 lines (89 loc) · 2.5 KB
/
urlShortener.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import nock from 'nock';
import { DataSource } from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import createOrGetConnection from '../src/db';
import {
GraphQLTestClient,
GraphQLTestingState,
MockContext,
disposeGraphQLTesting,
initializeGraphQLTesting,
testQueryErrorCode,
} from './helpers';
import { getShortUrl } from '../src/common';
let con: DataSource;
let state: GraphQLTestingState;
let client: GraphQLTestClient;
let loggedUser: string = null;
jest.mock('../src/common', () => ({
...jest.requireActual('../src/common'),
getShortUrl: jest.fn(),
}));
const mockGetShortUrl = getShortUrl as jest.MockedFunction<typeof getShortUrl>;
mockGetShortUrl.mockImplementation(
async (): Promise<string> =>
Promise.resolve(`https://diy.dev/${uuidv4().slice(0, 8)}`),
);
beforeAll(async () => {
con = await createOrGetConnection();
state = await initializeGraphQLTesting(
() => new MockContext(con, loggedUser),
);
client = state.client;
});
beforeEach(async () => {
loggedUser = '1';
nock.cleanAll();
mockGetShortUrl.mockClear();
});
afterAll(() => disposeGraphQLTesting(state));
describe('query getShortUrl', () => {
const QUERY = `
query GetShortUrl($url: String!) {
getShortUrl(url: $url)
}
`;
it('should not work for unauthenticated users', () => {
loggedUser = null;
testQueryErrorCode(
client,
{
query: QUERY,
variables: { url: 'hh::/not-a-valid-url.test' },
},
'UNAUTHENTICATED',
);
expect(mockGetShortUrl).not.toHaveBeenCalled();
});
it('should not work for invalid URL', () => {
testQueryErrorCode(
client,
{
query: QUERY,
variables: { url: 'hh::/not-a-valid-url.test' },
},
'GRAPHQL_VALIDATION_FAILED',
);
expect(mockGetShortUrl).not.toHaveBeenCalled();
});
it('should not work for URL not pointing to daily.dev', () => {
testQueryErrorCode(
client,
{
query: QUERY,
variables: { url: 'https://not-a-valid-url.test' },
},
'GRAPHQL_VALIDATION_FAILED',
);
expect(mockGetShortUrl).not.toHaveBeenCalled();
});
it('should generate shortened URL', async () => {
const url = new URL('/foo/bar', process.env.COMMENTS_PREFIX).toString();
const res = await client.query(QUERY, { variables: { url } });
expect(res.errors).toBeFalsy();
expect(mockGetShortUrl).toHaveBeenCalled();
expect(res.data.getShortUrl).toMatch(
new RegExp(`https://diy.dev/[0-9a-f]{8}$`, 'i'),
);
});
});