Skip to content

Commit

Permalink
refactor: modularize setup and simplify submission creation test
Browse files Browse the repository at this point in the history
- Move test data initialization to  to reduce redundancy.
- Extract submission document creation to .
- Simplify main test body to focus on core assertions.
  • Loading branch information
viniblack committed Nov 11, 2024
1 parent 3dfefe0 commit 8d435e0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 57 deletions.
52 changes: 25 additions & 27 deletions tests/modalSubmissionLesson.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ jest.mock('react-i18next', () => ({
jest.mock('../lib/user')
jest.mock('../lib/cohorts')

describe('Check if submit link is calling mintNFT function', () => {
describe('Modal - NFT Submission', () => {
const mockOnClose = jest.fn()
const mockCourse = { id: 'Rust_State_Machine' }
const mockSubmissionTitle = 'Upload Assignment'
const mockSubmissionText = 'Submit your assignment'
const mockSubmissionType = 'text'
const lessonSubmission = {
cohort_id: 'RU5mLpQrZZWlmftNSB2w',
content: { type: 'text', value: 'Conteúdo aleatório para teste' },
Expand All @@ -44,47 +41,50 @@ describe('Check if submit link is calling mintNFT function', () => {
kickoffEndTime: Date.now() + 86400000 * 7 + 3600000,
}

beforeAll(() => {
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve({ data: 'fake data' }) })
)
global.IntersectionObserver = class {
observe() {}
unobserve() {}
disconnect() {}
}
})

beforeEach(() => {
const setupMocks = () => {
jest.clearAllMocks()
getAllCohorts.mockResolvedValue([mockCohort])
getCurrentCohort.mockReturnValue(mockCohort)
getUserFromFirestore.mockResolvedValue(mockUser)
auth.currentUser = { uid: mockUser.uid }
})
}

const setupModal = () => {
const renderModal = () => {
render(
<Modal
openExternal
onClose={mockOnClose}
course={mockCourse}
lesson={lessonSubmission.lesson}
section={lessonSubmission.section}
submissionType={mockSubmissionType}
submissionTitle={mockSubmissionTitle}
submissionText={mockSubmissionText}
submissionType="text"
submissionTitle="Upload Assignment"
submissionText="Submit your assignment"
/>
)
}

it('should submit lesson correctly and create NFT', async () => {
beforeAll(() => {
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve({ data: 'fake data' }) })
)
global.IntersectionObserver = class {
observe() {}
unobserve() {}
disconnect() {}
}
})

beforeEach(() => {
setupMocks()
auth.currentUser = { uid: mockUser.uid }
})

it('should submit lesson correctly and call mintNFT function', async () => {
const submitLessonSpy = jest.spyOn(require('../lib/user'), 'submitLessonInFirestore')
const change = { data: () => lessonSubmission }
const context = { params: { lessonId: 'test-lesson-id' } }

setupModal()

renderModal()
await waitFor(async () => {
const textarea = screen.getByRole('textbox')
fireEvent.change(textarea, { target: { value: lessonSubmission.content.value } })
Expand All @@ -93,7 +93,6 @@ describe('Check if submit link is calling mintNFT function', () => {
const submitButton = screen.getByText('send')
fireEvent.click(submitButton)

// Verificar se submitLessonInFirestore foi chamada com os parâmetros corretos
expect(submitLessonSpy).toHaveBeenCalledWith(
lessonSubmission.cohort_id,
mockUser,
Expand All @@ -102,7 +101,6 @@ describe('Check if submit link is calling mintNFT function', () => {
lessonSubmission.content,
undefined
)

await mintNFT(change, context)
expect(mintNFT).toHaveBeenCalledWith(change, context)
})
Expand Down
62 changes: 32 additions & 30 deletions tests/submissionLesson.test.js
Original file line number Diff line number Diff line change
@@ -1,61 +1,63 @@
import { faker } from '@faker-js/faker';
import { db } from '../firebase/initFirebase';
import { doc, setDoc, serverTimestamp, getDoc } from 'firebase/firestore';
import { mintNFT } from '../functions/index';
import { faker } from '@faker-js/faker'
import { db } from '../firebase/initFirebase'
import { doc, setDoc, serverTimestamp, getDoc } from 'firebase/firestore'
import { mintNFT } from '../functions/index'

jest.mock('../functions/index', () => ({
mintNFT: jest.fn().mockResolvedValue(undefined),
}));
}))

describe('mintNFT Function', () => {
let lessonSubmission;
let change;
let context;
let lessonSubmission, change, context

beforeEach(() => {
const randomContent = faker.string.alpha(10);
setupTestData()
})

const setupTestData = () => {
lessonSubmission = {
cohort_id: 'RU5mLpQrZZWlmftNSB2w',
content: {
type: 'text',
value: randomContent,
value: faker.string.alpha(10),
},
createdAt: serverTimestamp(),
lesson: 'Lesson_2_Add_State.md',
section: 'Section_1',
user: 'users/23WEoArqzRf4ORh4cdvadaVsYtj1',
user_id: '23WEoArqzRf4ORh4cdvadaVsYtj1',
};
change = { data: () => lessonSubmission };
context = { params: { lessonId: 'test-lesson-id' } };
});

it('should create a submission document in lessons_submissions', async () => {
const submissionId = faker.string.uuid();
const docRef = doc(db, 'lessons_submissions', submissionId);
}
change = { data: () => lessonSubmission }
context = { params: { lessonId: 'test-lesson-id' } }
}

const createSubmissionDocument = async (submissionId) => {
const docRef = doc(db, 'lessons_submissions', submissionId)
await setDoc(docRef, {
...lessonSubmission,
cohort: doc(db, `cohorts/${lessonSubmission.cohort_id}`),
user: doc(db, lessonSubmission.user),
});
})
return docRef
}

const submissionDoc = await getDoc(docRef);
expect(submissionDoc.exists()).toBe(true);
const data = submissionDoc.data();
it('should create a submission document in lessons_submissions', async () => {
const submissionId = faker.string.uuid()
const docRef = await createSubmissionDocument(submissionId)

// Verify the created document's structure
expect(data).toMatchObject({
const submissionDoc = await getDoc(docRef)
expect(submissionDoc.exists()).toBe(true)
expect(submissionDoc.data()).toMatchObject({
cohort_id: lessonSubmission.cohort_id,
content: lessonSubmission.content,
createdAt: expect.any(Object),
lesson: lessonSubmission.lesson,
section: lessonSubmission.section,
user_id: lessonSubmission.user_id,
});
})

// Check if Firestore trigger is called
await mintNFT(change, context);
expect(mintNFT).toHaveBeenCalledWith(change, context);
});
});
// Check if Firestore trigger (mintNFT) is called
await mintNFT(change, context)
expect(mintNFT).toHaveBeenCalledWith(change, context)
})
})

0 comments on commit 8d435e0

Please sign in to comment.