This repository has been archived by the owner on Jun 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
accessToken.test.ts
78 lines (69 loc) · 2.45 KB
/
accessToken.test.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
import type { Token, TokenResponse } from "../../src/helper/accessToken";
import fc from "fast-check";
import * as fcutil from "../_util/fcutil";
import nock from "nock";
import updateAccessToken from "../../src/helper/accessToken";
// Mocking
import * as creds from "../../src/helper/api/creds";
jest.mock("../../src/helper/api/creds");
const postForm = creds.postForm as jest.Mock;
// Just in case something slips through, don't actually ping reddit.
beforeAll(() => nock.disableNetConnect());
afterAll(() => nock.enableNetConnect());
function token(offset: { max?: number; min?: number }): fc.Arbitrary<Token> {
return fc.record({
access: fc.string(),
expiration: fc.integer(offset).map(i => i + Date.now()),
});
}
function tknResponse(): fc.Arbitrary<TokenResponse> {
return fc.record({
accessToken: fc.string(),
tokenType: fc.string(),
expiresIn: fc.integer({ min: 1000, max: 10000 }),
scope: fc.string(),
});
}
describe("updateAccessToken()", () => {
it("should return the token if it hasn't expired", async () => {
await fc.assert(
fc.asyncProperty(
token({ min: 1000 }),
fcutil.auth(),
fcutil.creds(),
fc.string(),
async (tkn, auth, creds, agent) => {
postForm.mockReset();
const prms = updateAccessToken(agent, tkn, creds, auth);
await expect(prms).resolves.toStrictEqual(tkn);
expect(postForm).not.toBeCalled();
}
)
);
});
it("should fetch a new token if the current one has expired", async () => {
await fc.assert(
fc.asyncProperty(
token({ max: -1000 }),
fcutil.auth(),
fcutil.creds(),
tknResponse(),
fc.string(),
async (tkn, auth, creds, newTkn, agent) => {
postForm.mockReset().mockReturnValue(newTkn);
const prms = await updateAccessToken(agent, tkn, creds, auth);
expect(postForm).toBeCalled();
expect(prms.access).toEqual(newTkn.accessToken);
expect(prms.expiration).toBeGreaterThan(Date.now());
}
)
);
});
xdescribe("grants", () => {
// TODO: Test that different auths request different grants.
// BODY: Using a TokenAuth should request a `refresh_token` grant. Using a
// BODY: UsernameAuth should request a `password` grant, and using no auth
// BODY: should request a client_credentials grant. This is currently
// BODY: pending https://github.com/nock/nock/issues/2171.
});
});