Skip to content

Commit

Permalink
Merge pull request #7 from Challe-P/testy-tests
Browse files Browse the repository at this point in the history
Testy tests
  • Loading branch information
Challe-P authored Oct 27, 2024
2 parents 0d60487 + 30c338a commit 7f2fc8e
Show file tree
Hide file tree
Showing 5 changed files with 208 additions and 2 deletions.
53 changes: 53 additions & 0 deletions src/__tests__/code-editor.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React from 'react';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import { getOne } from "../models/fetch.js";
import { useParams } from 'react-router-dom';
import UpdateDoc from '../update-doc.jsx';
import { runCode } from "../models/exec";

// Mock the navigate function for delete function
jest.mock('react-router-dom', () => ({
useParams: jest.fn(),
useNavigate: jest.fn(),
}));

// Mock the getOne function
jest.mock("../models/fetch", () => ({
getOne: jest.fn()
}));

jest.mock("../models/exec", () => ({
runCode: jest.fn()
}));

describe('Tests code editor', () => {

beforeAll(() => {
jest.spyOn(console, 'error').mockImplementation(jest.fn());
});

afterAll(() => {
global.console.error.mockRestore();
jest.clearAllMocks();
});

test('tests that the run code function gets called correctly', async () => {
useParams.mockReturnValue({id: "091823901283"});
const mockResponse = {title: "Fake title", content: "console.log('Test')", mode: "code"};
getOne.mockResolvedValue(mockResponse);
runCode.mockReturnValue("Test");

await act(async () => {
render(<UpdateDoc />);
});

await act(async () => {
fireEvent.click(screen.getByRole('button', { name: /Run code/i }));
});

expect(runCode).toHaveBeenCalledWith("console.log('Test')");
const codeOutput = document.getElementsByClassName('code-output')[0];
expect(codeOutput).toBeInTheDocument;
expect(codeOutput.textContent).toBe("Test");
});
});
29 changes: 29 additions & 0 deletions src/__tests__/exec.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { runCode } from "../models/exec";

// Mocking fetch to test module without network connections
global.fetch = jest.fn();

describe('Test suite for exec module', () => {
beforeEach(() => {
fetch.mockClear();
});

test('Testing that runCode gets called correctly.', async () => {
const code = "console.log('Test')";
const mockedResult = {data: btoa('Test')}
const sentData = {code: btoa(code)};

fetch.mockResolvedValueOnce({
json: jest.fn().mockResolvedValue(mockedResult)
});
const response = await runCode(code);

expect(fetch).toHaveBeenCalledWith("https://execjs.emilfolino.se/code", {
body: JSON.stringify(sentData),
headers: { 'content-type': 'application/json' },
method: 'POST',
});

expect(response).toEqual("Test")
});
});
48 changes: 48 additions & 0 deletions src/__tests__/quill-editor.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React from 'react';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import { getOne } from "../models/fetch.js";
import { useParams } from 'react-router-dom';
import UpdateDoc from '../update-doc.jsx';
import { runCode } from "../models/exec";
import userEvent from "@testing-library/user-event";
import Delta from 'quill-delta';

// Mock the navigate function for delete function
jest.mock('react-router-dom', () => ({
useParams: jest.fn(),
useNavigate: jest.fn(),
}));

// Mock the getOne function
jest.mock("../models/fetch", () => ({
getOne: jest.fn()
}));

jest.mock("../models/exec", () => ({
runCode: jest.fn()
}));

describe('Tests quill editor', () => {

beforeAll(() => {
jest.spyOn(console, 'error').mockImplementation(jest.fn());
});

afterAll(() => {
global.console.error.mockRestore();
jest.clearAllMocks();
});

test('tests that loading document with delta content works', async () => {
useParams.mockReturnValue({id: "091823901283"});
const delta = new Delta({ops: [{"insert": "Fake delta content "}]})
const mockResponse = {title: "Fake title", content: delta, mode: "text"};
getOne.mockResolvedValue(mockResponse);
await act(async () => {
render(<UpdateDoc />);
});

expect(screen.getByLabelText('Title')).toHaveValue('Fake title');
expect(document.getElementsByClassName('ql-editor')[0].textContent).toContain('Fake delta content');
});
});
79 changes: 77 additions & 2 deletions src/__tests__/socket.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ describe('Socket tests', () => {

io.mockReturnValue(socketMock);
});

afterAll(() => {
jest.clearAllMocks();
});
Expand Down Expand Up @@ -114,10 +115,84 @@ describe('Socket tests', () => {
quillInstance.root.dispatchEvent(new Event('text-change'));
});
const emittedDelta = new Delta({ops: [{"retain": 5}, {"insert": "emitted "}]})

expect(socketMock.emit).toHaveBeenCalledWith("doc", {id: "091823901283", content: emittedDelta, user: undefined, title: "Fake title", mode: "text"});
});

// Tests that the socket behaves properly when a component dismounts
// Tests that the data is handled correctly when socket sends text to text
test('socket onDoc text from text', async () => {
useParams.mockReturnValue({id: "091823901283"});
const mockResponse = {title: "Fake title", content: "Fake content", mode: "text"};
getOne.mockResolvedValue(mockResponse);
const emittedDelta = new Delta({ops: [{"retain": 5}, {"insert": "emitted "}]})
await act(async () => {
render(<UpdateDoc />);
});
await act(() => {
const onDoc = socketMock.on.mock.calls.find(call => call[0] === 'doc')[1];
onDoc({title: "Ondoc faked", content: emittedDelta, mode: "text", user: "apan"});
});

await screen.findByText('Fake emitted content');
const quillEditor = document.getElementsByClassName('ql-container')[0];
const quillInstance = Quill.find(quillEditor);
expect(quillInstance).toBeInstanceOf(Quill);
expect(quillInstance.getText()).toBe("Fake emitted content\n");
});

test('Tests taht socket onDoc works from code to code', async () =>{
useParams.mockReturnValue({id: "091823901283"});
const mockResponse = {title: "Fake title", content: "Fake content", mode: "code"};
getOne.mockResolvedValue(mockResponse);
await act(async () => {
render(<UpdateDoc />);
});
await act(() => {
const onDoc = socketMock.on.mock.calls.find(call => call[0] === 'doc')[1];
onDoc({content: "console.log('test')", mode: "code", user: "apan"});
});
// expect codemirror to exist and content to be correct
expect(document.querySelector('.cm-content')).toBeInTheDocument();
expect(document.querySelector('.cm-content').textContent).toBe("console.log('test')")
});


test('Tests that onDoc changes from text to code when receiving code data', async () =>{
useParams.mockReturnValue({id: "091823901283"});
const mockResponse = {title: "Fake title", content: "Fake content", mode: "text"};
getOne.mockResolvedValue(mockResponse);
await act(async () => {
render(<UpdateDoc />);
});
await act(() => {
const onDoc = socketMock.on.mock.calls.find(call => call[0] === 'doc')[1];
onDoc({content: "console.log('test')", mode: "code", user: "apan"});
});
// expect codemirror to exist and content to be correct
expect(document.querySelector('.cm-content')).toBeInTheDocument();
expect(document.querySelector('.cm-content').textContent).toBe("console.log('test')");
});

test('Tests that onDoc changes from code to text when receiving text data', async () => {
useParams.mockReturnValue({id: "091823901283"});
const mockResponse = {title: "Fake title", content: "Fake content", mode: "code"};
getOne.mockResolvedValue(mockResponse);
const emittedDelta = new Delta({ops: [{"insert": "Wow, this is text, not code!"}]})

await act(async () => {
render(<UpdateDoc />);
});

await act(() => {
const onDoc = socketMock.on.mock.calls.find(call => call[0] === 'doc')[1];
onDoc({title: "Ondoc faked", content: emittedDelta, mode: "text", user: "apan"});
});

const quillEditor = document.getElementsByClassName('ql-container')[0];
const quillInstance = Quill.find(quillEditor);
expect(quillInstance).toBeInstanceOf(Quill);
expect(quillInstance.getText()).toBe("Wow, this is text, not code!\n");
})

// Sending pure text with socket doesn't work with text editor

});
1 change: 1 addition & 0 deletions src/forms/code-editor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export function CodeEditor({ content, setContent, setDelta, setDeltaIsLatest, ti
socket.off('doc', onDoc)
}
});

const onChange = (value, viewUpdate) => {
setContent(value);
setDeltaIsLatest(false);
Expand Down

0 comments on commit 7f2fc8e

Please sign in to comment.