Skip to content

Commit

Permalink
tests
Browse files Browse the repository at this point in the history
  • Loading branch information
DimitriB01 committed Sep 12, 2024
1 parent e22b4d7 commit 4bb17b5
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ const AlgorithmSettingsModal = (props: AlgorithmSettingsModalProps): JSX.Element
//change hardcoded teacher selection to fetched teacher selection
const [teacherSelection, setTeacherSelection] = useState(0)
const { t } = useTranslation()
const options = (
props.options ?? [...(t('components.AlgorithmSettingsModal.algorithms', { returnObjects: true }) as optionsType)]
).slice(1)
const options =
props.options ??
[...(t('components.AlgorithmSettingsModal.algorithms', { returnObjects: true }) as optionsType)].slice(1)
const handleSelect = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setSelected(parseInt(event.target.value))
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Home/Home.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('Test the Home page', () => {
)

await waitFor(() => {
expect(container.innerHTML).toContain('pages.home.noCourses')
expect(container.innerHTML).toContain('MuiSkeleton')
})
})

Expand Down Expand Up @@ -84,7 +84,7 @@ describe('Test the Home page', () => {
)

await waitFor(() => {
expect(container.innerHTML).toContain('pages.home.noCourses')
expect(container.innerHTML).toContain('MuiSkeleton')
})
})

Expand Down
12 changes: 6 additions & 6 deletions src/services/RemoteCourses/fetchRemoteCourses.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ global.fetch = jest.fn(() =>
})
) as jest.Mock

describe('fetchCourses has expected behaviour', () => {
it('should return the course when the response is successful', async () => {
describe('fetchRemoteCourses has expected behaviour', () => {
it('should return the remote course when the response is successful', async () => {
const expectedData = [
{
enddate: 1702166400,
Expand Down Expand Up @@ -59,27 +59,27 @@ describe('fetchCourses has expected behaviour', () => {
const expectedError = 'Error: HTTP error undefined'
const expectedMessage = 'Error: HTTP error undefined'

const mockResponse = {
const mockResponseRemoteCourse = {
ok: false,
json: jest.fn().mockResolvedValue({ error: expectedError, message: expectedMessage })
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
fetch.mockResolvedValue(mockResponse)
fetch.mockResolvedValue(mockResponseRemoteCourse)

await expect(fetchRemoteCourses()).rejects.toThrow(`${expectedMessage}`)
})

it('should throw an unknown error when the response does not have an error variable', async () => {
const mockResponse = {
const mockResponseRemoteCourse = {
ok: false,
json: jest.fn().mockResolvedValue({})
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
fetch.mockResolvedValue(mockResponse)
fetch.mockResolvedValue(mockResponseRemoteCourse)

await expect(fetchRemoteCourses()).rejects.toThrow('')
})
Expand Down
136 changes: 136 additions & 0 deletions src/services/RemoteTopics/fetchRemoteTopics.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { getConfig } from '@shared'
import { fetchRemoteTopics } from './fetchRemoteTopics'

global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ status: 200 }),
ok: true,
headers: {
get: () => 'application/json'
}
})
) as jest.Mock

describe('fetchRemoteTopics has expected behaviour', () => {
it('should return the course when the response is successful', async () => {
const expectedData = [
{
lms_learning_elements: [
{
lms_activity_type: 'forum',
lms_id: 1,
lms_learning_element_name: 'Announcements'
},
{
lms_activity_type: 'feedback',
lms_id: 3,
lms_learning_element_name: 'ILS Fragebogen'
},
{
lms_activity_type: 'book',
lms_id: 12,
lms_learning_element_name: 'hello'
},
{
lms_activity_type: 'resource',
lms_id: 38,
lms_learning_element_name: '978-3-658-35492-3 (1)'
},
{
lms_activity_type: 'h5pactivity',
lms_id: 39,
lms_learning_element_name: '645ccebe93872995e83c744e'
}
],
topic_lms_id: 1,
topic_lms_name: 'General'
},
{
lms_learning_elements: [
{
lms_activity_type: 'h5pactivity',
lms_id: 4,
lms_learning_element_name: 'DefinitionDeklaration und AufrufeinerFunktion'
}
],
topic_lms_id: 2,
topic_lms_name: 'Bekannte'
},
{
lms_learning_elements: [
{
lms_activity_type: 'lti',
lms_id: 7,
lms_learning_element_name: 'haski_lti_thingy'
},
{
lms_activity_type: 'h5pactivity',
lms_id: 8,
lms_learning_element_name: 'Adapter - Kurzübersicht'
},
{
lms_activity_type: 'h5pactivity',
lms_id: 10,
lms_learning_element_name: 'Adapter - leicht 1'
},
{
lms_activity_type: 'h5pactivity',
lms_id: 9,
lms_learning_element_name: 'Adapter - leicht 2'
}
],
topic_lms_id: 3,
topic_lms_name: 'Strat'
}
]

const mockResponseRemoteTopic = {
ok: true,
json: jest.fn().mockResolvedValue(expectedData)
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
fetch.mockResolvedValue(mockResponseRemoteTopic)

const result = await fetchRemoteTopics('1')

expect(fetch).toHaveBeenCalledWith(`${getConfig().BACKEND}/lms/remote/course/1/content`, {
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
})
expect(result).toEqual(expectedData)
})

it('should throw a specific error when the response has an error variable', async () => {
const expectedError = 'Error: HTTP error undefined'
const expectedMessage = 'Error: HTTP error undefined'

const mockResponseRemoteTopic = {
ok: false,
json: jest.fn().mockResolvedValue({ error: expectedError, message: expectedMessage })
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
fetch.mockResolvedValue(mockResponseRemoteTopic)

await expect(fetchRemoteTopics()).rejects.toThrow(`${expectedMessage}`)
})

it('should throw an unknown error when the response does not have an error variable', async () => {
const mockResponseRemoteTopic = {
ok: false,
json: jest.fn().mockResolvedValue({})
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
fetch.mockResolvedValue(mockResponseRemoteTopic)

await expect(fetchRemoteTopics()).rejects.toThrow('')
})
})
1 change: 1 addition & 0 deletions src/services/RemoteTopics/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { fetchRemoteTopics } from './fetchRemoteTopics'
72 changes: 27 additions & 45 deletions src/services/RoleContext/RoleContext.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import '@testing-library/jest-dom'
import { render, renderHook } from '@testing-library/react'
import { useContext } from 'react'
import RoleContext, { AuthContextType } from './RoleContext'
import { Typography } from '@common/components'
import RoleContext, { RoleContextType } from './RoleContext'

global.fetch = jest.fn(() =>
Promise.resolve({
Expand All @@ -13,74 +14,55 @@ global.fetch = jest.fn(() =>
})
) as jest.Mock

describe('Test Authcontext', () => {
describe('Test Rolecontext', () => {
// render custom component
const TestComponent = () => {
const context = useContext(RoleContext)
return (
<>
{context.isAuth ? (
<button onClick={() => context.logout()}>Logout</button>
{context.isStudentRole ? (
<Typography>Your are a student</Typography>
) : context.isCourseCreatorRole ? (
<Typography>Your are a course creator</Typography>
) : (
<button onClick={() => context.setExpire(Math.round(new Date().getTime() / 1000) + 1000)}>Login</button>
<Typography>You have no role</Typography>
)}
</>
)
}
const providedContext = {
isAuth: false,
setExpire: jest.fn(),
logout: jest.fn()
} as AuthContextType
it('should render unauthorized', () => {
const studentContext = {
isStudentRole: true,
isCourseCreatorRole: false
} as RoleContextType

const courseCreatorContext = {
isStudentRole: false,
isCourseCreatorRole: true
} as RoleContextType

it('student role, should render text', () => {
const renderResult = render(
<RoleContext.Provider value={providedContext}>
<RoleContext.Provider value={studentContext}>
<TestComponent />
</RoleContext.Provider>
)
expect(renderResult.getByText('Login')).toBeInTheDocument()
renderResult.getByText('Login').click()
expect(providedContext.setExpire).toBeCalled()
expect(renderResult.getByText('Your are a student')).toBeInTheDocument()
})

it('should render authorized', () => {
it('course creator role, should render text', () => {
const renderResult = render(
<RoleContext.Provider value={{ ...providedContext, isAuth: true }}>
<RoleContext.Provider value={courseCreatorContext}>
<TestComponent />
</RoleContext.Provider>
)
expect(renderResult.getByText('Logout')).toBeInTheDocument()
renderResult.getByText('Logout').click()
expect(providedContext.logout).toBeCalled()
expect(renderResult.getByText('Your are a course creator')).toBeInTheDocument()
})

it('should return the default props of AuthContext', () => {
it('should return the default props of RoleContext', () => {
const context = renderHook(() => useContext(RoleContext))
expect(context.result.current).toMatchObject({
isAuth: false,
setExpire: expect.any(Function),
logout: expect.any(Function)
isStudentRole: false,
isCourseCreatorRole: false
})
})

test('should change isAuth to true', () => {
const renderResult = render(
<RoleContext.Provider value={{ ...providedContext }}>
<TestComponent />
</RoleContext.Provider>
)
renderResult.getByText('Login').click()
expect(providedContext.setExpire).toBeCalled()
})

test('should change isAuth to false', () => {
const context = renderHook(() => useContext(RoleContext))
context.result.current.setExpire(0)
expect(context.result.current.isAuth).toBe(false)
})

it('should call default logout', () => {
const context = renderHook(() => useContext(RoleContext))
context.result.current.logout()
})
})

0 comments on commit 4bb17b5

Please sign in to comment.