-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathset_property.test.js
88 lines (62 loc) · 2.75 KB
/
set_property.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Import necessary dependencies
import '@testing-library/jest-dom';
import 'jest-fetch-mock';
import { jest } from '@jest/globals';
const $ = require('jquery');
global.$ = $;
const module = require('planttracer');
const set_property = module.set_property
// Mock dependencies
global.$ = require('jquery');
fetchMock.enableMocks();
describe('set_property function', () => {
const api_key = 'test_api_key';
const API_BASE = 'https://example.com/';
const user_id = 'user123';
const movie_id = 'movie456';
const property = 'watched';
const value = 'true';
beforeEach(() => {
fetch.resetMocks();
document.body.innerHTML = '<div id="message"></div>';
global.api_key = api_key;
global.API_BASE = API_BASE;
global.list_ready_function = jest.fn();
});
it('should call fetch with the correct URL and form data', async () => {
fetch.mockResponseOnce(JSON.stringify({ error: false }));
set_property(user_id, movie_id, property, value);
await new Promise(process.nextTick); // Wait for async code
expect(fetch).toHaveBeenCalledWith(`${API_BASE}api/set-metadata`, expect.objectContaining({
method: 'POST',
body: expect.any(FormData),
}));
const formData = fetch.mock.calls[0][1].body;
expect(formData.get("api_key")).toBe(api_key);
expect(formData.get("set_user_id")).toBe(user_id);
expect(formData.get("set_movie_id")).toBe(movie_id);
expect(formData.get("property")).toBe(property);
expect(formData.get("value")).toBe(value);
});
it('should display error message if API response has an error', async () => {
const errorMessage = 'Invalid data';
fetch.mockResponseOnce(JSON.stringify({ error: true, message: errorMessage }));
set_property(user_id, movie_id, property, value);
await new Promise(process.nextTick); // Wait for async code
expect(document.getElementById('message').innerHTML).toBe(`error: ${errorMessage}`);
});
it('should call list_ready_function if API response has no error', async () => {
fetch.mockResponseOnce(JSON.stringify({ error: false }));
set_property(user_id, movie_id, property, value);
await new Promise(process.nextTick); // Wait for async code
expect(global.list_ready_function).toHaveBeenCalledTimes(0);
});
it('should catch and log errors on fetch failure', async () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
fetch.mockReject(() => Promise.reject("API Failure"));
set_property(user_id, movie_id, property, value);
await new Promise(process.nextTick); // Wait for async code
expect(consoleSpy).toHaveBeenCalledWith("API Failure");
consoleSpy.mockRestore();
});
});