Best JavaScript code snippet using ng-mocks
form.js
Source:form.js
1import $ from 'dom7';2import { window, document } from 'ssr-window';3import Utils from '../../utils/utils';4// Form Data5const FormData = {6 store(form, data) {7 const app = this;8 let formId = form;9 const $formEl = $(form);10 if ($formEl.length && $formEl.is('form') && $formEl.attr('id')) {11 formId = $formEl.attr('id');12 }13 // Store form data in app.formsData14 app.form.data[`form-${formId}`] = data;15 // Store form data in local storage also16 try {17 window.localStorage[`f7form-${formId}`] = JSON.stringify(data);18 } catch (e) {19 throw e;20 }21 },22 get(form) {23 const app = this;24 let formId = form;25 const $formEl = $(form);26 if ($formEl.length && $formEl.is('form') && $formEl.attr('id')) {27 formId = $formEl.attr('id');28 }29 try {30 if (window.localStorage[`f7form-${formId}`]) {31 return JSON.parse(window.localStorage[`f7form-${formId}`]);32 }33 } catch (e) {34 throw e;35 }36 if (app.form.data[`form-${formId}`]) {37 return app.form.data[`form-${formId}`];38 }39 return undefined;40 },41 remove(form) {42 const app = this;43 let formId = form;44 const $formEl = $(form);45 if ($formEl.length && $formEl.is('form') && $formEl.attr('id')) {46 formId = $formEl.attr('id');47 }48 // Delete form data from app.formsData49 if (app.form.data[`form-${formId}`]) {50 app.form.data[`form-${formId}`] = '';51 delete app.form.data[`form-${formId}`];52 }53 // Delete form data from local storage also54 try {55 if (window.localStorage[`f7form-${formId}`]) {56 window.localStorage[`f7form-${formId}`] = '';57 window.localStorage.removeItem(`f7form-${formId}`);58 }59 } catch (e) {60 throw e;61 }62 },63};64// Form Storage65const FormStorage = {66 init(formEl) {67 const app = this;68 const $formEl = $(formEl);69 const formId = $formEl.attr('id');70 if (!formId) return;71 const initialData = app.form.getFormData(formId);72 if (initialData) {73 app.form.fillFromData($formEl, initialData);74 }75 function store() {76 const data = app.form.convertToData($formEl);77 if (!data) return;78 app.form.storeFormData(formId, data);79 $formEl.trigger('form:storedata', data);80 app.emit('formStoreData', $formEl[0], data);81 }82 $formEl.on('change submit', store);83 },84 destroy(formEl) {85 const $formEl = $(formEl);86 $formEl.off('change submit');87 },88};89// Form To/From Data90function formToData(formEl) {91 const app = this;92 const $formEl = $(formEl).eq(0);93 if ($formEl.length === 0) return undefined;94 // Form data95 const data = {};96 // Skip input types97 const skipTypes = ['submit', 'image', 'button', 'file'];98 const skipNames = [];99 $formEl.find('input, select, textarea').each((inputIndex, inputEl) => {100 const $inputEl = $(inputEl);101 if ($inputEl.hasClass('ignore-store-data') || $inputEl.hasClass('no-store-data')) {102 return;103 }104 const name = $inputEl.attr('name');105 const type = $inputEl.attr('type');106 const tag = inputEl.nodeName.toLowerCase();107 if (skipTypes.indexOf(type) >= 0) return;108 if (skipNames.indexOf(name) >= 0 || !name) return;109 if (tag === 'select' && $inputEl.prop('multiple')) {110 skipNames.push(name);111 data[name] = [];112 $formEl.find(`select[name="${name}"] option`).each((index, el) => {113 if (el.selected) data[name].push(el.value);114 });115 } else {116 switch (type) {117 case 'checkbox':118 skipNames.push(name);119 data[name] = [];120 $formEl.find(`input[name="${name}"]`).each((index, el) => {121 if (el.checked) data[name].push(el.value);122 });123 break;124 case 'radio':125 skipNames.push(name);126 $formEl.find(`input[name="${name}"]`).each((index, el) => {127 if (el.checked) data[name] = el.value;128 });129 break;130 default:131 data[name] = $inputEl.val();132 break;133 }134 }135 });136 $formEl.trigger('form:todata', data);137 app.emit('formToData', $formEl[0], data);138 return data;139}140function formFromData(formEl, formData) {141 const app = this;142 const $formEl = $(formEl).eq(0);143 if (!$formEl.length) return;144 let data = formData;145 const formId = $formEl.attr('id');146 if (!data && formId) {147 data = app.form.getFormData(formId);148 }149 if (!data) return;150 // Skip input types151 const skipTypes = ['submit', 'image', 'button', 'file'];152 const skipNames = [];153 $formEl.find('input, select, textarea').each((inputIndex, inputEl) => {154 const $inputEl = $(inputEl);155 if ($inputEl.hasClass('ignore-store-data') || $inputEl.hasClass('no-store-data')) {156 return;157 }158 const name = $inputEl.attr('name');159 const type = $inputEl.attr('type');160 const tag = inputEl.nodeName.toLowerCase();161 if (typeof data[name] === 'undefined' || data[name] === null) return;162 if (skipTypes.indexOf(type) >= 0) return;163 if (skipNames.indexOf(name) >= 0 || !name) return;164 if (tag === 'select' && $inputEl.prop('multiple')) {165 skipNames.push(name);166 $formEl.find(`select[name="${name}"] option`).each((index, el) => {167 const selectEl = el;168 if (data[name].indexOf(el.value) >= 0) selectEl.selected = true;169 else selectEl.selected = false;170 });171 } else {172 switch (type) {173 case 'checkbox':174 skipNames.push(name);175 $formEl.find(`input[name="${name}"]`).each((index, el) => {176 const checkboxEl = el;177 if (data[name].indexOf(el.value) >= 0) checkboxEl.checked = true;178 else checkboxEl.checked = false;179 });180 break;181 case 'radio':182 skipNames.push(name);183 $formEl.find(`input[name="${name}"]`).each((index, el) => {184 const radioEl = el;185 if (data[name] === el.value) radioEl.checked = true;186 else radioEl.checked = false;187 });188 break;189 default:190 $inputEl.val(data[name]);191 break;192 }193 }194 if (tag === 'select' || tag === 'input' || tag === 'textarea') {195 $inputEl.trigger('change', 'fromdata');196 }197 });198 $formEl.trigger('form:fromdata', data);199 app.emit('formFromData', $formEl[0], data);200}201function initAjaxForm() {202 const app = this;203 function onSubmitChange(e, fromData) {204 const $formEl = $(this);205 if (e.type === 'change' && !$formEl.hasClass('form-ajax-submit-onchange')) return;206 if (e.type === 'submit') e.preventDefault();207 if (e.type === 'change' && fromData === 'fromdata') return;208 const method = ($formEl.attr('method') || 'GET').toUpperCase();209 const contentType = $formEl.prop('enctype') || $formEl.attr('enctype');210 const url = $formEl.attr('action');211 if (!url) return;212 let data;213 if (method === 'POST') {214 if (contentType === 'application/x-www-form-urlencoded') {215 data = app.form.convertToData($formEl[0]);216 } else {217 data = new window.FormData($formEl[0]);218 }219 } else {220 data = Utils.serializeObject(app.form.convertToData($formEl[0]));221 }222 app.request({223 method,224 url,225 contentType,226 data,227 beforeSend(xhr) {228 $formEl.trigger('formajax:beforesend', { data, xhr });229 app.emit('formAjaxBeforeSend', $formEl[0], data, xhr);230 },231 error(xhr) {232 $formEl.trigger('formajax:error', { data, xhr });233 app.emit('formAjaxError', $formEl[0], data, xhr);234 },235 complete(xhr) {236 $formEl.trigger('formajax:complete', { data, xhr });237 app.emit('formAjaxComplete', $formEl[0], data, xhr);238 },239 success(response, status, xhr) {240 $formEl.trigger('formajax:success', { data, xhr });241 app.emit('formAjaxSuccess', $formEl[0], data, xhr);242 },243 });244 }245 $(document).on('submit change', 'form.form-ajax-submit, form.form-ajax-submit-onchange', onSubmitChange);246}247export default {248 name: 'form',249 create() {250 const app = this;251 Utils.extend(app, {252 form: {253 data: {},254 storeFormData: FormData.store.bind(app),255 getFormData: FormData.get.bind(app),256 removeFormData: FormData.remove.bind(app),257 convertToData: formToData.bind(app),258 fillFromData: formFromData.bind(app),259 storage: {260 init: FormStorage.init.bind(app),261 destroy: FormStorage.destroy.bind(app),262 },263 },264 });265 },266 on: {267 init() {268 const app = this;269 initAjaxForm.call(app);270 },271 tabBeforeRemove(tabEl) {272 const app = this;273 $(tabEl).find('.form-store-data').each((index, formEl) => {274 app.form.storage.destroy(formEl);275 });276 },277 tabMounted(tabEl) {278 const app = this;279 $(tabEl).find('.form-store-data').each((index, formEl) => {280 app.form.storage.init(formEl);281 });282 },283 pageBeforeRemove(page) {284 const app = this;285 page.$el.find('.form-store-data').each((index, formEl) => {286 app.form.storage.destroy(formEl);287 });288 },289 pageInit(page) {290 const app = this;291 page.$el.find('.form-store-data').each((index, formEl) => {292 app.form.storage.init(formEl);293 });294 },295 },...
Using AI Code Generation
1import { FormEl } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4 let fixture: ComponentFixture<MyComponent>;5 let component: MyComponent;6 beforeEach(() => {7 TestBed.configureTestingModule({8 });9 fixture = TestBed.createComponent(MyComponent);10 component = fixture.componentInstance;11 });12 it('should have a form', () => {13 const form = FormEl(fixture.debugElement);14 expect(form).toBeDefined();15 });16});17import { getControl } from 'ng-mocks';18import { MyComponent } from './my.component';19describe('MyComponent', () => {20 let fixture: ComponentFixture<MyComponent>;21 let component: MyComponent;22 beforeEach(() => {23 TestBed.configureTestingModule({24 });25 fixture = TestBed.createComponent(MyComponent);26 component = fixture.componentInstance;27 });28 it('should have a control', () => {29 const control = getControl(fixture.debugElement, 'username');30 expect(control).toBeDefined();31 });32});33import { getControlValue } from 'ng-mocks';34import { MyComponent } from './my.component';35describe('MyComponent', () => {36 let fixture: ComponentFixture<MyComponent>;37 let component: MyComponent;38 beforeEach(() => {39 TestBed.configureTestingModule({40 });41 fixture = TestBed.createComponent(MyComponent);42 component = fixture.componentInstance;43 });44 it('should have a control', () => {45 const value = getControlValue(fixture.debugElement, 'username');46 expect(value).toBe('default');47 });48});
Using AI Code Generation
1import { FormEl } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4 it('should work', () => {5 const fixture = MockRender(MyComponent);6 const form = FormEl(fixture.debugElement);7 expect(form).toBeDefined();8 });9});10import { MockBuilder, MyComponent } from 'ng-mocks';11describe('MyComponent', () => {12 beforeEach(() => MockBuilder(MyComponent));13 it('should work', () => {14 const fixture = MockRender(MyComponent);15 const form = FormEl(fixture.debugElement);16 expect(form).toBeDefined();17 });18});19import { MockRender, MyComponent } from 'ng-mocks';20describe('MyComponent', () => {21 it('should work', () => {22 const fixture = MockRender(MyComponent);23 const form = FormEl(fixture.debugElement);24 expect(form).toBeDefined();25 });26});27import { MockInstance, MyComponent } from 'ng-mocks';28describe('MyComponent', () => {29 it('should work', () => {30 const fixture = MockRender(MyComponent);31 const instance = MockInstance(MyComponent, fixture.debugElement);32 expect(instance).toBeDefined();33 });34});35import { MockProvider, MyComponent } from 'ng-mocks';36describe('MyComponent', () => {37 beforeEach(() => MockBuilder(MyComponent).mock(MyService));38 it('should work', () => {39 const fixture = MockRender(MyComponent);40 const provider = MockProvider(MyService, fixture.debugElement);41 expect(provider).toBeDefined();42 });43});44import { MockDirective, MyComponent } from 'ng-mocks';45describe('MyComponent', () => {46 beforeEach(() => MockBuilder(MyComponent).mock(MyDirective
Using AI Code Generation
1import { FormEl } from 'ng-mocks';2const fixture = MockRender(`3`);4const form = FormEl(fixture.debugElement);5import { MockBuilder } from 'ng-mocks';6beforeEach(() => MockBuilder(MyComponent, MyModule));7import { MockRender } from 'ng-mocks';8beforeEach(() => MockRender(MyComponent, MyModule));9import { MockInstance } from 'ng-mocks';10beforeEach(() => MockInstance(MyComponent, MyModule));11import { MockService } from 'ng-mocks';12beforeEach(() => MockService(MyComponent, MyModule));13import { MockProvider } from 'ng-mocks';14beforeEach(() => MockProvider(MyComponent, MyModule));15import { MockDirective } from 'ng-mocks';16beforeEach(() => MockDirective(MyComponent, MyModule));17import { MockPipe } from 'ng-mocks';18beforeEach(() => MockPipe(MyComponent, MyModule));19import { MockComponent } from 'ng-mocks';20beforeEach(() => MockComponent(MyComponent, MyModule));21import { MockModule } from 'ng-mocks';22beforeEach(() => MockModule(My
Using AI Code Generation
1import { FormEl } from 'ng-mocks';2import { AppComponent } from './app.component';3describe('AppComponent', () => {4 it('should have an input', () => {5 const fixture = MockRender(AppComponent);6 const input = FormEl(fixture.debugElement, 'input');7 expect(input).toBeDefined();8 });9});10import { FormElAll } from 'ng-mocks';11import { AppComponent } from './app.component';12describe('AppComponent', () => {13 it('should have an input', () => {14 const fixture = MockRender(AppComponent);15 const inputs = FormElAll(fixture.debugElement, 'input');16 expect(inputs.length).toBe(2);17 });18});19import { FormElAll } from 'ng-mocks';20import { AppComponent } from './app.component';21describe('AppComponent', () => {22 it('should have an input', () => {23 const fixture = MockRender(AppComponent);24 const inputs = FormElAll(fixture.debugElement, 'input');25 expect(inputs.length).toBe(2);26 });27});28import { FormElGroup } from 'ng-mocks';29import { AppComponent } from './app.component';30describe('AppComponent', () => {31 it('should have a form group', () => {32 const fixture = MockRender(AppComponent);33 const formGroup = FormElGroup(fixture.debugElement);34 expect(formGroup).toBeDefined();35 });36});37import { FormElValue } from 'ng-mocks';38import { AppComponent } from './app.component';
Using AI Code Generation
1var formEl = ngMocks.formEl('<form name="testForm"></form>');2var formEl = ngMocks.formEl('<form name="testForm"></form>');3var formEl = ngMocks.formEl('<form name="testForm"></form>');4var formEl = ngMocks.formEl('<form name="testForm"></form>');5var formEl = ngMocks.formEl('<form name="testForm"></form>');6var formEl = ngMocks.formEl('<form name="testForm"></form>');7var formEl = ngMocks.formEl('<form name="testForm"></form>');8var formEl = ngMocks.formEl('<form name="testForm"></form>');9var formEl = ngMocks.formEl('<form name="testForm"></form>');10var formEl = ngMocks.formEl('<form name="testForm"></form>');11var formEl = ngMocks.formEl('<form name="testForm"></form>');12var formEl = ngMocks.formEl('<form name="testForm"></form>');13var formEl = ngMocks.formEl('<form name="testForm"></form>');14var formEl = ngMocks.formEl('<form name="testForm"></form>');15var formEl = ngMocks.formEl('<form name="testForm"></form>');16var formEl = ngMocks.formEl('<form name="testForm"></form>');
Using AI Code Generation
1import { formEl } from 'ng-mocks';2describe('FormEl', () => {3 it('should get the form element', () => {4 const fixture = MockRender(`5 `);6 const form = formEl(fixture.debugElement);7 expect(form).toBeDefined();8 });9});10import { formGroupEl } from 'ng-mocks';11describe('FormGroupEl', () => {12 it('should get the form group element', () => {13 const fixture = MockRender(`14 `);15 const formGroup = formGroupEl(fixture.debugElement);16 expect(formGroup).toBeDefined();17 });18});19import { inputEl } from 'ng-mocks';20describe('InputEl', () => {21 it('should get the input element', () => {22 const fixture = MockRender(`23 `);24 const input = inputEl(fixture.debugElement);25 expect(input).toBeDefined();26 });27});28import { inputElByName } from 'ng-mocks';29describe('InputElByName', () => {30 it('should get the input element by name', () => {31 const fixture = MockRender(`32 `);33 const input = inputElByName(fixture.debugElement, 'name');34 expect(input).toBeDefined();35 });36});37import { inputElByLabel } from 'ng-mocks';38describe('InputElByLabel', () => {39 it('should get the input element by label', () => {40 const fixture = MockRender(`
Using AI Code Generation
1import { FormEl } from 'ng-mocks';2const formEl = FormEl(fixture.debugElement);3const form = formEl.componentInstance;4const formGroup = formEl.formGroup;5const formControl = formEl.formControl;6import { MockControl } from 'ng-mocks';7const mockControl = MockControl.create();8const formControl = mockControl.formControl;9import { MockComponent } from 'ng-mocks';10const mockComponent = MockComponent(MyComponent);11import { MockDirective } from 'ng-mocks';12const mockDirective = MockDirective(MyDirective);13import { MockModule } from 'ng-mocks';14const mockModule = MockModule(MyModule);15import { MockPipe } from 'ng-mocks';16const mockPipe = MockPipe(MyPipe);17import { MockRender } from 'ng-mocks';18const fixture = MockRender(MyComponent);19import { MockService } from 'ng-mocks';20const mockService = MockService(MyService);21import { MockHelper } from 'ng-mocks';22const mockHelper = MockHelper(MyComponent);23import { MockInstance } from 'ng-mocks';24const mockInstance = MockInstance(MyComponent, MyService);
Using AI Code Generation
1describe('Component: test', function() {2 var formEl, scope, element, $httpBackend;3 beforeEach(module('app'));4 beforeEach(module('app/test/test.html'));5 beforeEach(inject(function($compile, $rootScope, _$httpBackend_) {6 scope = $rootScope.$new();7 $httpBackend = _$httpBackend_;8 element = angular.element('<test></test>');9 element = $compile(element)(scope);10 scope.$apply();11 formEl = element.find('form');12 }));13 it('should render the form', function() {14 expect(formEl).toBeDefined();15 });16 it('should render the form with the correct fields', function() {17 expect(formEl.find('input').length).toBe(3);18 expect(formEl.find('input')[0].name).toBe('name');19 expect(formEl.find('input')[1].name).toBe('email');20 expect(formEl.find('input')[2].name).toBe('password');21 });22 it('should render the form with the correct labels', function() {23 expect(formEl.find('label').length).toBe(3);24 expect(formEl.find('label')[0].textContent).toContain('Name');25 expect(formEl.find('label')[1].textContent).toContain('Email');26 expect(formEl.find('label')[2].textContent).toContain('Password');27 });28 it('should render the form with the correct placeholders', function() {29 expect(formEl.find('input').length).toBe(3);30 expect(formEl.find('input')[0].placeholder).toBe('Name');31 expect(formEl.find('input')[1].placeholder).toBe('Email');32 expect(formEl.find('input')[2].placeholder).toBe('Password');33 });34 it('should render the form with the correct buttons', function() {35 expect(formEl.find('button').length).toBe(2);36 expect(formEl.find('button')[0].textContent).toContain('Submit');37 expect(formEl.find('button')[1].textContent).toContain('Reset');38 });39 it('should render the form with the correct submit button type', function() {40 expect(formEl.find('button')[0].type).toBe('submit');41 });42 it('should render the form with the correct reset button type', function() {43 expect(formEl.find('button')[1].type).toBe('reset');44 });45 it('should
Using AI Code Generation
1var formEl = ngMocks.formEl;2var fixture = ngMocks.find('my-component');3var form = formEl(fixture);4var control = form.control('myControl');5expect(control).toBeDefined();6find(selector: string): ComponentFixture<any>7var ngMocks = require('ng-mocks');8var fixture = ngMocks.find('my-component');9expect(fixture.componentInstance).toBeDefined();10flush(): void11var ngMocks = require('ng-mocks');12ngMocks.flush();13formEl(fixture: ComponentFixture<any>): NgForm14var ngMocks = require('ng-mocks');15var fixture = ngMocks.find('my-component');16var form = ngMocks.formEl(fixture);17var control = form.control('myControl');18expect(control).toBeDefined();19input(fixture: ComponentFixture<any>, name: string, value: any): void20var ngMocks = require('ng-mocks');21var fixture = ngMocks.find('my-component');22ngMocks.input(fixture, 'myControl', 'my value');23expect(fixture.componentInstance.myControl).toEqual('my value');24instance(fixture: ComponentFixture<any>): any25var ngMocks = require('ng-mocks');26var fixture = ngMocks.find('my-component');27var component = ngMocks.instance(fixture);28expect(component).toBeDefined();29mock<T>(type: Type<T>): MockRenderResult<T>
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!