|
| 1 | +import ScriptLoader from './script-loader'; |
| 2 | + |
| 3 | +describe('ScriptLoader', () => { |
| 4 | + let loader: ScriptLoader; |
| 5 | + let script: HTMLScriptElement; |
| 6 | + |
| 7 | + beforeEach(() => { |
| 8 | + script = document.createElement('script'); |
| 9 | + |
| 10 | + jest.spyOn(document, 'createElement').mockImplementation(() => script); |
| 11 | + jest.spyOn(document.body, 'appendChild').mockImplementation((element) => |
| 12 | + element.onreadystatechange(new Event('readystatechange')) |
| 13 | + ); |
| 14 | + |
| 15 | + loader = new ScriptLoader(document); |
| 16 | + }); |
| 17 | + |
| 18 | + afterEach(() => { |
| 19 | + jest.restoreAllMocks(); |
| 20 | + }); |
| 21 | + |
| 22 | + it('attaches script tag to document', async () => { |
| 23 | + await loader.loadScript('https://code.jquery.com/jquery-3.2.1.min.js'); |
| 24 | + |
| 25 | + expect(document.body.appendChild).toHaveBeenCalledWith(script); |
| 26 | + expect(script.src).toEqual('https://code.jquery.com/jquery-3.2.1.min.js'); |
| 27 | + }); |
| 28 | + |
| 29 | + it('resolves promise if script is loaded', async () => { |
| 30 | + const output = await loader.loadScript('https://code.jquery.com/jquery-3.2.1.min.js'); |
| 31 | + |
| 32 | + expect(output).toBeInstanceOf(Event); |
| 33 | + }); |
| 34 | + |
| 35 | + it('rejects promise if script is not loaded', async () => { |
| 36 | + jest.spyOn(document.body, 'appendChild').mockImplementation( |
| 37 | + (element) => element.onerror(new Event('error')) |
| 38 | + ); |
| 39 | + |
| 40 | + try { |
| 41 | + await loader.loadScript('https://code.jquery.com/jquery-3.2.1.min.js'); |
| 42 | + } catch (output) { |
| 43 | + expect(output).toBeInstanceOf(Event); |
| 44 | + } |
| 45 | + }); |
| 46 | +}); |
0 commit comments