Skip to content
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
wants to merge 69 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
8797e09
added test cases
pranshustuff Oct 20, 2024
4d7b7dd
Merge pull request #1 from pranshustuff/new_branch
pranshustuff Oct 20, 2024
8f99e07
added signIn test
pranshustuff Oct 20, 2024
f831a3f
Create test.yml
pranshustuff Oct 21, 2024
e1a66b3
Update test.yml
pranshustuff Oct 21, 2024
26dec9b
Update test.yml
pranshustuff Oct 21, 2024
af50d1c
Update test.yml
pranshustuff Oct 21, 2024
1d8cb6b
Update test.yml
pranshustuff Oct 21, 2024
c6ef26f
Update test.yml
pranshustuff Oct 21, 2024
089609b
Update test.yml
pranshustuff Oct 21, 2024
ff0c713
Update test.yml
pranshustuff Oct 21, 2024
4edd954
Update test.yml
pranshustuff Oct 21, 2024
4c87a38
Update builder.yml
pranshustuff Oct 21, 2024
951a533
Update test.yml
pranshustuff Oct 21, 2024
456fac7
Update test.yml
pranshustuff Oct 21, 2024
48919b3
Update test.yml
pranshustuff Oct 21, 2024
5fd26a5
added sign Out test
pranshustuff Oct 21, 2024
7025a7d
modified signOut
pranshustuff Oct 22, 2024
16a32b0
test yml file
pranshustuff Oct 22, 2024
1081f51
yarn lock change
pranshustuff Oct 22, 2024
ec3288e
added test for isAuthenticated
pranshustuff Oct 22, 2024
6ff681f
added isAuth test to github actions
pranshustuff Oct 22, 2024
16a9773
Update builder.yml
pranshustuff Oct 22, 2024
286f5fd
added test for getBasicUserInfo
pranshustuff Oct 22, 2024
1d99e60
Merge branch 'main' of https://github.com/pranshustuff/asgardeo-auth-…
pranshustuff Oct 22, 2024
45995ed
modified test.yml
pranshustuff Oct 22, 2024
a434400
added test for refreshAccessToken
pranshustuff Oct 22, 2024
2fb5b9c
added accesstoken test in test.yml
pranshustuff Oct 22, 2024
2d46316
tsconfig changes
pranshustuff Oct 25, 2024
ecd9cbc
added new tests
pranshustuff Oct 25, 2024
846e67d
modified github action files
pranshustuff Oct 25, 2024
0e86faf
npm install fixes
pranshustuff Oct 25, 2024
8469a85
streamlined testing
pranshustuff Oct 25, 2024
a8c3c3e
lol
pranshustuff Oct 25, 2024
9829131
debugged test.yml
pranshustuff Oct 25, 2024
29953bd
Update test.yml
pranshustuff Oct 25, 2024
b6a98f1
Update test.yml
pranshustuff Oct 25, 2024
b6d8127
Update test.yml
pranshustuff Oct 25, 2024
73d3a19
something man idk
pranshustuff Oct 25, 2024
751aa38
Merge branch 'main' of https://github.com/asgardeo/asgardeo-auth-reac…
pranshustuff Oct 25, 2024
0c7e64c
Update lib/src/api.ts
pranshustuff Nov 1, 2024
fd6c5f0
Update test.yml
pranshustuff Nov 1, 2024
7a2808c
Update test.yml
pranshustuff Nov 1, 2024
8ea011c
Update test.yml
pranshustuff Nov 1, 2024
edff456
Update test.yml
pranshustuff Nov 1, 2024
824972a
Update test.yml
pranshustuff Nov 1, 2024
6b3afdb
Update test.yml
pranshustuff Nov 1, 2024
c78e80a
Update test.yml
pranshustuff Nov 1, 2024
51bb503
Update test.yml
pranshustuff Nov 1, 2024
392f875
Update test.yml
pranshustuff Nov 1, 2024
3a683f4
Update test.yml
pranshustuff Nov 1, 2024
f694dd3
Update test.yml
pranshustuff Nov 1, 2024
58b2688
Update test.yml
pranshustuff Nov 1, 2024
a931e25
Update test.yml
pranshustuff Nov 1, 2024
6245da9
installed dependencies
pranshustuff Nov 1, 2024
362b272
removed break line in .babelrc
pranshustuff Nov 1, 2024
412ec02
Update test.yml
pranshustuff Nov 1, 2024
c519fd2
Update test.yml
pranshustuff Nov 1, 2024
d369302
Update test.yml
pranshustuff Nov 1, 2024
03f6931
Update test.yml
pranshustuff Nov 1, 2024
41680b8
changing node version to see if things work
pranshustuff Nov 1, 2024
ee8cb8e
maybe installing dependencies differently will help
pranshustuff Nov 1, 2024
b5dc2cb
hopefully crypto works now
pranshustuff Nov 1, 2024
b0d997b
maybe jest.setup.js was the problem
pranshustuff Nov 1, 2024
a591606
some changes to see if things work
pranshustuff Nov 1, 2024
340a809
god knows at this point
pranshustuff Nov 1, 2024
ae7b6a4
Update test.yml
pranshustuff Nov 1, 2024
ce1890b
added license header to unit test files
pranshustuff Nov 1, 2024
eb67501
Merge branch 'main' into main
pranshustuff Dec 13, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{"presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"]}

Copy link
Member

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.

39 changes: 39 additions & 0 deletions .github/workflows/test.yml
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
6 changes: 6 additions & 0 deletions lib/jest.config.js
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
};

27 changes: 27 additions & 0 deletions lib/jest.setup.js
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;
12 changes: 8 additions & 4 deletions lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"types": "dist/types/src/index.d.ts",
"module": "dist/main.js",
"scripts": {
"test": "jest",
"lint": "eslint --ext .js,.ts .",
"fix-lint": "eslint --ext .js,.ts . --fix",
"build": "rimraf dist && yarn run type-check && webpack --env NODE_ENV=production",
Expand Down Expand Up @@ -48,28 +49,31 @@
},
"devDependencies": {
"@babel/cli": "^7.19.3",
"@babel/core": "^7.20.5",
"@babel/core": "^7.26.0",
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/plugin-proposal-decorators": "^7.20.5",
"@babel/plugin-transform-modules-commonjs": "^7.19.6",
"@babel/preset-env": "^7.20.2",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.18.6",
"@babel/preset-env": "^7.26.0",
"@babel/preset-react": "^7.25.9",
"@babel/preset-typescript": "^7.26.0",
"@babel/runtime-corejs3": "^7.20.6",
"@types/node": "^18.11.17",
"@typescript-eslint/eslint-plugin": "^5.47.0",
"@typescript-eslint/parser": "^5.47.0",
"babel-jest": "^29.7.0",
"babel-loader": "^9.1.0",
"core-js": "^3.26.1",
"eslint": "^8.30.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-react": "^7.31.11",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-webpack-plugin": "^3.2.0",
"jest-environment-jsdom": "^29.7.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rimraf": "^3.0.2",
"typescript": "^4.9.4",
"util": "^0.12.5",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"worker-loader": "^3.0.8"
Expand Down
6 changes: 6 additions & 0 deletions lib/tests/__mocks__/@asgardeo/auth_spa.js
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(),
};

52 changes: 52 additions & 0 deletions lib/tests/authComponent.test.js
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();
});
});
78 changes: 78 additions & 0 deletions lib/tests/getUserInfo.test.js
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);
});
});
67 changes: 67 additions & 0 deletions lib/tests/isAuth.test.js
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);
});
});
Loading