import serialize from './objectToFormData'; const options = { indices: true, dotNotation: true, allowEmptyArrays: true, noFileListBrackets: true, }; const formDataAppend = global.FormData.prototype.append; beforeEach(() => { global.FormData.prototype.append = jest.fn(formDataAppend); }); describe('Object To Form Data', () => { it('properly serializes a simple object', () => { const object = { name: 'Bob', age: 20, }; const result = serialize(object, options); expect(result.get('name')).toBe(object.name); expect(result.get('age')).toBe('20'); }); it('properly serializes an object with a non-file array property', () => { const object = { name: 'Bob', age: 20, favoriteFoods: ['Hamburger', 'Pizza'], }; const result = serialize(object, options); expect(result.get('name')).toBe(object.name); expect(result.has('favoriteFoods[0]')).toBe(true); expect(result.get('favoriteFoods[0]')).toBe('Hamburger'); expect(result.has('favoriteFoods[1]')).toBe(true); expect(result.get('favoriteFoods[1]')).toBe('Pizza'); }); it('properly serializes a file in a form', () => { const object = { a: new File(['foo'], 'foo.txt', { type: 'text/plain', }), }; const result = serialize(object, options); expect(result.has('a')).toBe(true); expect(result.get('a')).toBeInstanceOf(File); }); it('properly serializes an object with a file array property', () => { const foo = new File(['foo'], 'foo.txt', { type: 'text/plain', }); const bar = new File(['bar'], 'bar.txt', { type: 'text/plain', }); const object = { fileArray: [foo, bar], }; const result = serialize(object, options); expect(result.append).toHaveBeenCalledTimes(2); expect(result.append).toHaveBeenNthCalledWith(1, 'fileArray', foo); expect(result.append).toHaveBeenNthCalledWith(2, 'fileArray', bar); expect(result.has('fileArray[]')).toBe(false); expect(result.has('fileArray[0]')).toBe(false); expect(result.has('fileArray[1]')).toBe(false); expect(result.has('fileArray')).toBe(true); expect(result.getAll('fileArray')).toEqual(object.fileArray); }); });