-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(identity): unit tests for services #369
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
f24128e
build(package/): installed jest-mock-axios
seaerchin a8615e1
build(package): installed ts-jest and removed jest config in package.…
seaerchin 1ed0369
test(jest.config,.js): added jest config
seaerchin d49aa98
test(authservice): add spec
seaerchin 07f614c
refactor(mailclient): changed mailclient so that initialization fails…
seaerchin e3bdb5b
test(mailclient): add tests and axios mock
seaerchin d47a1fa
refactor(constants): add constants for tests
seaerchin 4203e6c
refactor(smsclient): change api key retrieval to be done at construct…
seaerchin 8baffb3
test(smsclient): add test
seaerchin 6721624
test(tokenstore): added tests
seaerchin 80c8e33
build(paths): add mocks to path
seaerchin da02df4
chore(tokenstore): update naming for clarity
seaerchin 3cea311
chore(totpgenerator): changed access values
seaerchin 60d6b65
test(totpgenerator): add tests
seaerchin 0781a2b
refactor(mailclient): changed mailclient initialization for better re…
seaerchin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
// This is a manual module mock for the AWS client. | ||
// This is done to prevent our internal services from pinging the actual AWS ones | ||
// and to ensure our tests are 1. consistent 2. reliable. | ||
|
||
export const mockSend = jest.fn() | ||
|
||
export const secretsManagerClient = { | ||
send: mockSend, | ||
} | ||
|
||
export const SecretsManagerClient: jest.Mock< | ||
typeof secretsManagerClient | ||
> = jest.fn().mockImplementation(() => secretsManagerClient) | ||
|
||
export const GetSecretValueCommand = jest.fn((secret) => ({ SecretId: secret })) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import mockAxios from "jest-mock-axios" | ||
|
||
export default mockAxios |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
// eslint-disable-next-line import/prefer-default-export | ||
export const totp = { | ||
clone: jest.fn().mockReturnThis(), | ||
generate: jest.fn(), | ||
verify: jest.fn(), | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ | ||
module.exports = { | ||
preset: "ts-jest", | ||
testEnvironment: "node", | ||
moduleNameMapper: { | ||
"^@root/(.*)": "<rootDir>/$1", | ||
"^@classes/(.*)": "<rootDir>/classes/$1", | ||
"^@errors/(.*)": "<rootDir>/errors/$1", | ||
"^@logger/(.*)": "<rootDir>/logger/$1", | ||
"^@middleware/(.*)": "<rootDir>/middleware/$1", | ||
"^@routes/(.*)": "<rootDir>/routes/$1", | ||
"^@utils/(.*)": "<rootDir>/utils/$1", | ||
"^@loaders/(.*)": "<rootDir>/loaders/$1", | ||
"^@database/(.*)": "<rootDir>/database/$1", | ||
"^@services/(.*)": "<rootDir>/services/$1", | ||
"^@validators/(.*)": "<rootDir>/validators/$1", | ||
"^@fixtures/(.*)": "<rootDir>/fixtures/$1", | ||
"^@mocks/(.*)": "<rootDir>/__mocks__/$1", | ||
}, | ||
} |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
import mockAxios from "jest-mock-axios" | ||
|
||
import { BadRequestError } from "@root/errors/BadRequestError" | ||
|
||
import _AuthService from "../AuthService" | ||
|
||
import { | ||
mockAccessToken, | ||
mockHeaders, | ||
mockSiteName, | ||
mockUserId, | ||
} from "./constants" | ||
|
||
const AuthService = new _AuthService({ axiosClient: mockAxios }) | ||
const mockEndpoint = `/${mockSiteName}/collaborators/${mockUserId}` | ||
|
||
describe("Auth Service", () => { | ||
afterEach(() => mockAxios.reset()) | ||
|
||
it("should call axios successfully and return true when the call is successful", async () => { | ||
// Arrange | ||
const expected = true | ||
mockAxios.get.mockResolvedValueOnce({ | ||
response: { status: 200 }, | ||
}) | ||
|
||
// Act | ||
const actual = await AuthService.hasAccessToSite( | ||
mockSiteName, | ||
mockUserId, | ||
mockAccessToken | ||
) | ||
|
||
// Assert | ||
expect(actual).toBe(expected) | ||
expect(mockAxios.get).toHaveBeenCalledWith(mockEndpoint, mockHeaders) | ||
}) | ||
|
||
it("should call axios successfully and return false when the call fails with 403", async () => { | ||
// Arrange | ||
const expected = false | ||
mockAxios.get.mockRejectedValueOnce({ | ||
response: { status: 403 }, | ||
// NOTE: Axios uses this property to determine if it's an axios error | ||
isAxiosError: true, | ||
}) | ||
|
||
// Act | ||
const actual = await AuthService.hasAccessToSite( | ||
mockSiteName, | ||
mockUserId, | ||
mockAccessToken | ||
) | ||
|
||
// Assert | ||
expect(actual).toBe(expected) | ||
expect(mockAxios.get).toHaveBeenCalledWith(mockEndpoint, mockHeaders) | ||
}) | ||
|
||
it("should call axios successfully and return false when the call fails with 404", async () => { | ||
// Arrange | ||
const expected = false | ||
mockAxios.get.mockRejectedValueOnce({ | ||
response: { status: 404 }, | ||
// NOTE: Axios uses this property to determine if it's an axios error | ||
isAxiosError: true, | ||
}) | ||
|
||
// Act | ||
const actual = await AuthService.hasAccessToSite( | ||
mockSiteName, | ||
mockUserId, | ||
mockAccessToken | ||
) | ||
|
||
// Assert | ||
expect(actual).toBe(expected) | ||
expect(mockAxios.get).toHaveBeenCalledWith(mockEndpoint, mockHeaders) | ||
}) | ||
|
||
it("should call axios successfully and bubble the error when the status is not 403 or 404", async () => { | ||
// Arrange | ||
const expected = { | ||
response: { status: 400 }, | ||
} | ||
mockAxios.get.mockRejectedValueOnce(new BadRequestError(expected)) | ||
|
||
// Act | ||
const actual = AuthService.hasAccessToSite( | ||
mockSiteName, | ||
mockUserId, | ||
mockAccessToken | ||
) | ||
|
||
// Assert | ||
expect(actual).rejects.toThrowError(new BadRequestError(expected)) | ||
expect(mockAxios.get).toHaveBeenCalledWith(mockEndpoint, mockHeaders) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
import mockAxios from "jest-mock-axios" | ||
|
||
import _MailClient from "../MailClient" | ||
|
||
import { mockRecipient, mockBody, mockHeaders } from "./constants" | ||
|
||
const mockEndpoint = "https://api.postman.gov.sg/v1/transactional/email/send" | ||
|
||
const MailClient = new _MailClient() | ||
|
||
const generateEmail = (recipient: string, body: string) => ({ | ||
subject: "One-Time Password (OTP) for IsomerCMS", | ||
from: "IsomerCMS <[email protected]>", | ||
body, | ||
recipient, | ||
}) | ||
|
||
describe("Mail Client", () => { | ||
const OLD_ENV = process.env | ||
|
||
beforeEach(() => { | ||
// Clears the cache so imports in tests uses a fresh copy | ||
jest.resetModules() | ||
// Make a copy of existing environment | ||
process.env = { ...OLD_ENV } | ||
}) | ||
|
||
afterAll(() => { | ||
// Restore old environment | ||
process.env = OLD_ENV | ||
}) | ||
|
||
afterEach(() => mockAxios.reset()) | ||
|
||
it("should return the result successfully when all parameters are valid", async () => { | ||
// Arrange | ||
mockAxios.post.mockResolvedValueOnce(200) | ||
|
||
// Act | ||
const actual = await MailClient.sendMail(mockRecipient, mockBody) | ||
|
||
// Assert | ||
expect(actual).toBeUndefined() | ||
expect(mockAxios.post).toHaveBeenCalledWith( | ||
mockEndpoint, | ||
generateEmail(mockRecipient, mockBody), | ||
mockHeaders | ||
) | ||
}) | ||
|
||
it("should throw an error on initialization when the env var is not set", async () => { | ||
// Arrange | ||
// Store the API key and set it later so that other tests are not affected | ||
const curApiKey = process.env.POSTMAN_API_KEY | ||
process.env.POSTMAN_API_KEY = "" | ||
// NOTE: This is because of typescript transpiling down to raw js | ||
// Export default compiles down to module.exports.default, which is also | ||
// done by babel. | ||
// Read more here: https://www.typescriptlang.org/tsconfig#allowSyntheticDefaultImports | ||
const _MailClientWithoutKey = (await import("../MailClient")).default | ||
|
||
// Act | ||
// NOTE: We require a new instance because the old one would already have the API key bound | ||
const actual = () => new _MailClientWithoutKey() | ||
|
||
// Assert | ||
expect(actual).toThrowError("Postman.gov.sg API key cannot be empty") | ||
process.env.POSTMAN_API_KEY = curApiKey | ||
expect(process.env.POSTMAN_API_KEY).toBe(curApiKey) | ||
}) | ||
|
||
it("should return an error when a network error occurs", async () => { | ||
// Arrange | ||
const generatedEmail = generateEmail(mockRecipient, mockBody) | ||
mockAxios.post.mockRejectedValueOnce("some error") | ||
|
||
// Act | ||
const actual = MailClient.sendMail(mockRecipient, mockBody) | ||
|
||
// Assert | ||
expect(actual).rejects.toThrowError("Failed to send email") | ||
expect(mockAxios.post).toHaveBeenCalledWith( | ||
mockEndpoint, | ||
generatedEmail, | ||
mockHeaders | ||
) | ||
}) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is ok for now - let's treat this as a work-in-progress.
I believe the end state we should aim for is to write MailClient in a dependency injectable way, so that we can invoke it more easily in our tests. Could we write this as a TODO comment in the MailClient file?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if by this you mean that the
POSTMAN_API_KEY
is given as a parameter to the constructor, i can do it here!There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's ok, we can leave it for now and add that to the various third-party client constructors in a separate PR/issue