-
Notifications
You must be signed in to change notification settings - Fork 92
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
Added unit tests for APIs, Secure App and AuthContext hook #263
Open
pranshustuff
wants to merge
69
commits into
asgardeo:main
Choose a base branch
from
pranshustuff:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+23,279
−1,362
Open
Changes from all commits
Commits
Show all changes
69 commits
Select commit
Hold shift + click to select a range
8797e09
added test cases
pranshustuff 4d7b7dd
Merge pull request #1 from pranshustuff/new_branch
pranshustuff 8f99e07
added signIn test
pranshustuff f831a3f
Create test.yml
pranshustuff e1a66b3
Update test.yml
pranshustuff 26dec9b
Update test.yml
pranshustuff af50d1c
Update test.yml
pranshustuff 1d8cb6b
Update test.yml
pranshustuff c6ef26f
Update test.yml
pranshustuff 089609b
Update test.yml
pranshustuff ff0c713
Update test.yml
pranshustuff 4edd954
Update test.yml
pranshustuff 4c87a38
Update builder.yml
pranshustuff 951a533
Update test.yml
pranshustuff 456fac7
Update test.yml
pranshustuff 48919b3
Update test.yml
pranshustuff 5fd26a5
added sign Out test
pranshustuff 7025a7d
modified signOut
pranshustuff 16a32b0
test yml file
pranshustuff 1081f51
yarn lock change
pranshustuff ec3288e
added test for isAuthenticated
pranshustuff 6ff681f
added isAuth test to github actions
pranshustuff 16a9773
Update builder.yml
pranshustuff 286f5fd
added test for getBasicUserInfo
pranshustuff 1d99e60
Merge branch 'main' of https://github.com/pranshustuff/asgardeo-auth-…
pranshustuff 45995ed
modified test.yml
pranshustuff a434400
added test for refreshAccessToken
pranshustuff 2fb5b9c
added accesstoken test in test.yml
pranshustuff 2d46316
tsconfig changes
pranshustuff ecd9cbc
added new tests
pranshustuff 846e67d
modified github action files
pranshustuff 0e86faf
npm install fixes
pranshustuff 8469a85
streamlined testing
pranshustuff a8c3c3e
lol
pranshustuff 9829131
debugged test.yml
pranshustuff 29953bd
Update test.yml
pranshustuff b6a98f1
Update test.yml
pranshustuff b6d8127
Update test.yml
pranshustuff 73d3a19
something man idk
pranshustuff 751aa38
Merge branch 'main' of https://github.com/asgardeo/asgardeo-auth-reac…
pranshustuff 0c7e64c
Update lib/src/api.ts
pranshustuff fd6c5f0
Update test.yml
pranshustuff 7a2808c
Update test.yml
pranshustuff 8ea011c
Update test.yml
pranshustuff edff456
Update test.yml
pranshustuff 824972a
Update test.yml
pranshustuff 6b3afdb
Update test.yml
pranshustuff c78e80a
Update test.yml
pranshustuff 51bb503
Update test.yml
pranshustuff 392f875
Update test.yml
pranshustuff 3a683f4
Update test.yml
pranshustuff f694dd3
Update test.yml
pranshustuff 58b2688
Update test.yml
pranshustuff a931e25
Update test.yml
pranshustuff 6245da9
installed dependencies
pranshustuff 362b272
removed break line in .babelrc
pranshustuff 412ec02
Update test.yml
pranshustuff c519fd2
Update test.yml
pranshustuff d369302
Update test.yml
pranshustuff 03f6931
Update test.yml
pranshustuff 41680b8
changing node version to see if things work
pranshustuff ee8cb8e
maybe installing dependencies differently will help
pranshustuff b5dc2cb
hopefully crypto works now
pranshustuff b0d997b
maybe jest.setup.js was the problem
pranshustuff a591606
some changes to see if things work
pranshustuff 340a809
god knows at this point
pranshustuff ae7b6a4
Update test.yml
pranshustuff ce1890b
added license header to unit test files
pranshustuff eb67501
Merge branch 'main' into main
pranshustuff 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,2 @@ | ||
{"presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"]} | ||
|
||
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,39 @@ | ||
name: Run Tests | ||
|
||
on: | ||
pull_request: | ||
push: | ||
|
||
jobs: | ||
test: | ||
runs-on: ubuntu-latest | ||
|
||
strategy: | ||
matrix: | ||
node-version: [18.x] | ||
|
||
steps: | ||
- name: Check out code | ||
uses: actions/checkout@v3 | ||
|
||
- name: Use Node.js | ||
uses: actions/setup-node@v3 | ||
with: | ||
node-version: '18.x' | ||
|
||
- name: Cache node modules | ||
uses: actions/cache@v3 | ||
with: | ||
path: node_modules | ||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} | ||
restore-keys: | | ||
${{ runner.os }}-node- | ||
|
||
- name: Install dependencies | ||
run: | | ||
npm install # Use npm ci for a clean install | ||
npm install --save-dev jest @testing-library/react @testing-library/jest-dom @babel/preset-env @babel/preset-react @babel/preset-typescript @testing-library/dom crypto-browserify | ||
|
||
- name: Run tests | ||
working-directory: ./lib | ||
run: npm test # Just run npm test, which should call jest |
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 @@ | ||
// jest.config.js | ||
module.exports = { | ||
testEnvironment: 'jsdom', // Ensure jsdom environment | ||
setupFilesAfterEnv: ['./jest.setup.js'], // Load jest.setup.js | ||
}; | ||
|
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,27 @@ | ||
// jest.setup.js | ||
|
||
// Polyfill for TextEncoder and TextDecoder | ||
const { TextEncoder, TextDecoder } = require('util'); | ||
|
||
global.crypto = { getRandomValues: (arr) => require('crypto').randomFillSync(arr) }; | ||
|
||
// Global definitions for TextEncoder and TextDecoder | ||
global.TextEncoder = TextEncoder; | ||
global.TextDecoder = TextDecoder; | ||
|
||
// Mock for Web Workers | ||
class MockWorker { | ||
constructor(stringUrl) { | ||
this.url = stringUrl; | ||
} | ||
postMessage(msg) { | ||
console.log('Message posted to worker:', msg); | ||
} | ||
terminate() { | ||
console.log('Worker terminated'); | ||
} | ||
addEventListener() {} | ||
removeEventListener() {} | ||
} | ||
|
||
global.Worker = MockWorker; |
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,6 @@ | ||
// __mocks__/@asgardeo/auth-spa.js | ||
export const AsgardeoSPAClient = { | ||
signIn: jest.fn(), | ||
isAuthenticated: 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,52 @@ | ||
/** | ||
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. | ||
* | ||
* WSO2 Inc. licenses this file to you under the Apache License, | ||
* Version 2.0 (the "License"); you may not use this file except | ||
* in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
import React from "react"; | ||
import { render, screen } from "@testing-library/react"; | ||
import { AuthenticatedComponent } from "../src/authenticated-component.tsx"; | ||
import { useAuthContext } from "../src/authenticate"; | ||
import "@testing-library/jest-dom"; | ||
|
||
jest.mock("../src/authenticate"); | ||
|
||
describe("AuthenticatedComponent", () => { | ||
it("renders children when authenticated", () => { | ||
useAuthContext.mockReturnValue({ state: { isAuthenticated: true } }); | ||
|
||
render( | ||
<AuthenticatedComponent fallback={<div data-testid="fallback">Fallback</div>}> | ||
<div data-testid="protected-content">Protected Content</div> | ||
</AuthenticatedComponent> | ||
); | ||
|
||
expect(screen.getByTestId("protected-content")).toBeInTheDocument(); | ||
}); | ||
|
||
it("renders fallback when not authenticated", () => { | ||
useAuthContext.mockReturnValue({ state: { isAuthenticated: false } }); | ||
|
||
render( | ||
<AuthenticatedComponent fallback={<div data-testid="fallback">Fallback</div>}> | ||
<div data-testid="protected-content">Protected Content</div> | ||
</AuthenticatedComponent> | ||
); | ||
|
||
expect(screen.getByTestId("fallback")).toBeInTheDocument(); | ||
expect(screen.queryByTestId("protected-content")).not.toBeInTheDocument(); | ||
}); | ||
}); |
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,78 @@ | ||
/** | ||
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. | ||
* | ||
* WSO2 Inc. licenses this file to you under the Apache License, | ||
* Version 2.0 (the "License"); you may not use this file except | ||
* in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
|
||
// Import the necessary modules | ||
import AuthAPI from '../src/api'; // Adjust the path as needed | ||
import { AsgardeoSPAClient } from '@asgardeo/auth-spa'; // Adjust the path as needed | ||
|
||
// Mock the AsgardeoSPAClient module | ||
jest.mock('@asgardeo/auth-spa', () => ({ | ||
AsgardeoSPAClient: { | ||
getInstance: jest.fn(), // Mock getInstance method | ||
}, | ||
})); | ||
|
||
describe('AuthAPI getBasicUserInfo()', () => { | ||
let authAPI; | ||
let mockClient; | ||
|
||
beforeEach(() => { | ||
// Step 1: Create a mock client with the getBasicUserInfo method | ||
mockClient = { | ||
getBasicUserInfo: jest.fn(), // Mock getBasicUserInfo | ||
}; | ||
|
||
// Step 2: Mock getInstance to return the mock client | ||
AsgardeoSPAClient.getInstance.mockReturnValue(mockClient); | ||
|
||
// Step 3: Instantiate AuthAPI (this will assign the mock client to _client) | ||
authAPI = new AuthAPI(); | ||
}); | ||
|
||
afterEach(() => { | ||
// Clear all mocks after each test | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
it('should return basic user information when getBasicUserInfo is called', async () => { | ||
// Arrange: Mock the resolved value for getBasicUserInfo | ||
const mockUserInfo = { | ||
username: 'john.doe', | ||
email: '[email protected]', | ||
}; | ||
mockClient.getBasicUserInfo.mockResolvedValue(mockUserInfo); | ||
|
||
// Act: Call the getBasicUserInfo method | ||
const result = await authAPI.getBasicUserInfo(); | ||
|
||
// Assert: Check if the result is the expected mockUserInfo | ||
expect(result).toEqual(mockUserInfo); | ||
expect(mockClient.getBasicUserInfo).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
it('should handle errors when getBasicUserInfo fails', async () => { | ||
// Arrange: Mock a rejected promise to simulate an error | ||
const mockError = new Error('Failed to fetch user info'); | ||
mockClient.getBasicUserInfo.mockRejectedValue(mockError); | ||
|
||
// Act & Assert: Expect the getBasicUserInfo method to throw the error | ||
await expect(authAPI.getBasicUserInfo()).rejects.toThrow('Failed to fetch user info'); | ||
expect(mockClient.getBasicUserInfo).toHaveBeenCalledTimes(1); | ||
}); | ||
}); |
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,67 @@ | ||
/** | ||
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. | ||
* | ||
* WSO2 Inc. licenses this file to you under the Apache License, | ||
* Version 2.0 (the "License"); you may not use this file except | ||
* in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
|
||
import AuthAPI from '../src/api'; // Adjust import if needed | ||
|
||
describe('AuthAPI isAuthenticated()', () => { | ||
let auth; | ||
let mockIsAuthenticated; | ||
|
||
beforeEach(() => { | ||
// Create a mock client object | ||
const mockClient = { | ||
isAuthenticated: jest.fn(), | ||
}; | ||
|
||
// Mock _client on the AuthAPI instance | ||
auth = new AuthAPI(); | ||
auth._client = mockClient; // Manually assign mock client here | ||
|
||
// Mock the isAuthenticated method on the mock client | ||
mockIsAuthenticated = auth._client.isAuthenticated; | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
afterEach(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
it('should return true when the user is authenticated', async () => { | ||
mockIsAuthenticated.mockResolvedValueOnce(true); | ||
|
||
const result = await auth.isAuthenticated(); | ||
|
||
expect(result).toBe(true); | ||
}); | ||
|
||
it('should return false when the user is not authenticated', async () => { | ||
mockIsAuthenticated.mockResolvedValueOnce(false); | ||
|
||
const result = await auth.isAuthenticated(); | ||
|
||
expect(result).toBe(false); | ||
}); | ||
|
||
it('should throw an error if isAuthenticated() fails', async () => { | ||
const errorMessage = 'Failed to check authentication'; | ||
mockIsAuthenticated.mockRejectedValueOnce(new Error(errorMessage)); | ||
|
||
await expect(auth.isAuthenticated()).rejects.toThrow(errorMessage); | ||
}); | ||
}); |
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.
Seems like there's an unwanted new line break here.
Check other places as well.