diff --git a/src/js/discord.js b/src/js/discord.js index fe90b10..2ebe6f6 100644 --- a/src/js/discord.js +++ b/src/js/discord.js @@ -10,20 +10,26 @@ function randomQuote(quote, crate) { crate.notify(the_quote); } -// Widgetbot initialization -loadScript('https://cdn.jsdelivr.net/npm/@widgetbot/crate@3', function() { - let widgetbot = new Crate({ - server: '804382334370578482', - channel: '804383092822900797', - defer: false, - }); +function initDiscord() { + loadScript('https://cdn.jsdelivr.net/npm/@widgetbot/crate@3', function() { + let widgetbot = new Crate({ + server: '804382334370578482', + channel: '804383092822900797', + defer: false, + }); - // get random video game quotes and notify the user on Widgetbot after 7 minutes - fetchRandomQuote().then(quote => { - setTimeout(() => { - if (widgetbot) { - randomQuote(quote, widgetbot); - } - }, 7 * 60 * 1000); + // get random video game quotes and notify the user on Widgetbot after 7 minutes + fetchRandomQuote().then(quote => { + setTimeout(() => { + if (widgetbot) { + randomQuote(quote, widgetbot); + } + }, 7 * 60 * 1000); + }); }); -}); +} + +module.exports = { + initDiscord, + randomQuote, +}; diff --git a/tests/discord.test.js b/tests/discord.test.js new file mode 100644 index 0000000..66528cd --- /dev/null +++ b/tests/discord.test.js @@ -0,0 +1,56 @@ +import { + describe, + expect, + it, + jest, +} from '@jest/globals'; + +const { initDiscord, randomQuote } = require('../src/js/discord'); +const loadScript = require('../src/js/load-script'); +const { fetchRandomQuote } = require('../src/js/random-quote'); + +jest.mock('../src/js/load-script'); +jest.mock('../src/js/random-quote'); + +describe('initDiscord', () => { + it('should load the script and get a random quote', () => { + jest.useFakeTimers(); + const mockCrate = { + notify: jest.fn() + }; + global.Crate = jest.fn(() => mockCrate); + + loadScript.mockImplementation((url, callback) => { + callback(); + }); + + fetchRandomQuote.mockResolvedValue({ + quote: 'Test quote', + quote_safe: 'Test quote safe' + }); + + initDiscord(); + + expect(global.Crate).toHaveBeenCalledWith({ + server: '804382334370578482', + channel: '804383092822900797', + defer: false, + }); + + // advance timers + jest.advanceTimersByTime(7 * 60 * 1000); + + expect(fetchRandomQuote).toHaveBeenCalled(); + }); +}); + +describe('randomQuote', () => { + it('should notify the user with the quote', () => { + const mockCrate = { + notify: jest.fn() + }; + + randomQuote({quote_safe: 'Test quote'}, mockCrate); + expect(mockCrate.notify).toHaveBeenCalledWith('Test quote'); + }); +});