How to use applyPayload method in ng-mocks

Best JavaScript code snippet using ng-mocks

Conflict.ts

Source:Conflict.ts Github

copy

Full Screen

1import { greaterOfTwoDates, uniqCombineObjArrays } from '@standardnotes/utils'2import { ImmutablePayloadCollection } from '../Collection/Payload/ImmutablePayloadCollection'3import { CreateDecryptedItemFromPayload, CreateItemFromPayload } from '../../Utilities/Item/ItemGenerator'4import { HistoryMap, historyMapFunctions } from '../History/HistoryMap'5import { ConflictStrategy } from '../../Abstract/Item/Types/ConflictStrategy'6import { PayloadsByDuplicating } from '../../Utilities/Payload/PayloadsByDuplicating'7import { PayloadContentsEqual } from '../../Utilities/Payload/PayloadContentsEqual'8import { FullyFormedPayloadInterface } from '../../Abstract/Payload'9import {10 isDecryptedPayload,11 isErrorDecryptingPayload,12 isDeletedPayload,13} from '../../Abstract/Payload/Interfaces/TypeCheck'14import { ContentType } from '@standardnotes/common'15import { SyncResolvedPayload } from './Utilities/SyncResolvedPayload'16import { ItemsKeyDelta } from './ItemsKeyDelta'17import { SourcelessSyncDeltaEmit } from './Abstract/DeltaEmit'18import { getIncrementedDirtyIndex } from '../DirtyCounter/DirtyCounter'19export class ConflictDelta {20 constructor(21 protected readonly baseCollection: ImmutablePayloadCollection,22 protected readonly basePayload: FullyFormedPayloadInterface,23 protected readonly applyPayload: FullyFormedPayloadInterface,24 protected readonly historyMap: HistoryMap,25 ) {}26 public result(): SourcelessSyncDeltaEmit {27 if (this.applyPayload.content_type === ContentType.ItemsKey) {28 const keyDelta = new ItemsKeyDelta(this.baseCollection, [this.applyPayload])29 return keyDelta.result()30 }31 const strategy = this.getConflictStrategy()32 return {33 emits: this.handleStrategy(strategy),34 ignored: [],35 }36 }37 getConflictStrategy(): ConflictStrategy {38 const isBaseErrored = isErrorDecryptingPayload(this.basePayload)39 const isApplyErrored = isErrorDecryptingPayload(this.applyPayload)40 if (isBaseErrored || isApplyErrored) {41 if (isBaseErrored && !isApplyErrored) {42 return ConflictStrategy.KeepBaseDuplicateApply43 } else if (!isBaseErrored && isApplyErrored) {44 return ConflictStrategy.DuplicateBaseKeepApply45 } else if (isBaseErrored && isApplyErrored) {46 return ConflictStrategy.KeepApply47 }48 } else if (isDecryptedPayload(this.basePayload)) {49 /**50 * Ensure no conflict has already been created with the incoming content.51 * This can occur in a multi-page sync request where in the middle of the request,52 * we make changes to many items, including duplicating, but since we are still not53 * uploading the changes until after the multi-page request completes, we may have54 * already conflicted this item.55 */56 const existingConflict = this.baseCollection.conflictsOf(this.applyPayload.uuid)[0]57 if (58 existingConflict &&59 isDecryptedPayload(existingConflict) &&60 isDecryptedPayload(this.applyPayload) &&61 PayloadContentsEqual(existingConflict, this.applyPayload)62 ) {63 /** Conflict exists and its contents are the same as incoming value, do not make duplicate */64 return ConflictStrategy.KeepBase65 } else {66 const tmpBaseItem = CreateDecryptedItemFromPayload(this.basePayload)67 const tmpApplyItem = CreateItemFromPayload(this.applyPayload)68 const historyEntries = this.historyMap[this.basePayload.uuid] || []69 const previousRevision = historyMapFunctions.getNewestRevision(historyEntries)70 return tmpBaseItem.strategyWhenConflictingWithItem(tmpApplyItem, previousRevision)71 }72 } else if (isDeletedPayload(this.basePayload) || isDeletedPayload(this.applyPayload)) {73 const baseDeleted = isDeletedPayload(this.basePayload)74 const applyDeleted = isDeletedPayload(this.applyPayload)75 if (baseDeleted && applyDeleted) {76 return ConflictStrategy.KeepApply77 } else {78 return ConflictStrategy.KeepApply79 }80 }81 throw Error('Unhandled strategy in Conflict Delta getConflictStrategy')82 }83 private handleStrategy(strategy: ConflictStrategy): SyncResolvedPayload[] {84 if (strategy === ConflictStrategy.KeepBase) {85 return this.handleKeepBaseStrategy()86 }87 if (strategy === ConflictStrategy.KeepApply) {88 return this.handleKeepApplyStrategy()89 }90 if (strategy === ConflictStrategy.KeepBaseDuplicateApply) {91 return this.handleKeepBaseDuplicateApplyStrategy()92 }93 if (strategy === ConflictStrategy.DuplicateBaseKeepApply) {94 return this.handleDuplicateBaseKeepApply()95 }96 if (strategy === ConflictStrategy.KeepBaseMergeRefs) {97 return this.handleKeepBaseMergeRefsStrategy()98 }99 throw Error('Unhandled strategy in conflict delta payloadsByHandlingStrategy')100 }101 private handleKeepBaseStrategy(): SyncResolvedPayload[] {102 const updatedAt = greaterOfTwoDates(this.basePayload.serverUpdatedAt, this.applyPayload.serverUpdatedAt)103 const updatedAtTimestamp = Math.max(this.basePayload.updated_at_timestamp, this.applyPayload.updated_at_timestamp)104 const leftPayload = this.basePayload.copyAsSyncResolved(105 {106 updated_at: updatedAt,107 updated_at_timestamp: updatedAtTimestamp,108 dirtyIndex: getIncrementedDirtyIndex(),109 dirty: true,110 lastSyncEnd: new Date(),111 },112 this.applyPayload.source,113 )114 return [leftPayload]115 }116 private handleKeepApplyStrategy(): SyncResolvedPayload[] {117 const result = this.applyPayload.copyAsSyncResolved(118 {119 lastSyncBegan: this.basePayload.lastSyncBegan,120 lastSyncEnd: new Date(),121 dirty: false,122 },123 this.applyPayload.source,124 )125 return [result]126 }127 private handleKeepBaseDuplicateApplyStrategy(): SyncResolvedPayload[] {128 const updatedAt = greaterOfTwoDates(this.basePayload.serverUpdatedAt, this.applyPayload.serverUpdatedAt)129 const updatedAtTimestamp = Math.max(this.basePayload.updated_at_timestamp, this.applyPayload.updated_at_timestamp)130 const leftPayload = this.basePayload.copyAsSyncResolved(131 {132 updated_at: updatedAt,133 updated_at_timestamp: updatedAtTimestamp,134 dirty: true,135 dirtyIndex: getIncrementedDirtyIndex(),136 lastSyncEnd: new Date(),137 },138 this.applyPayload.source,139 )140 const rightPayloads = PayloadsByDuplicating({141 payload: this.applyPayload,142 baseCollection: this.baseCollection,143 isConflict: true,144 source: this.applyPayload.source,145 })146 return [leftPayload].concat(rightPayloads)147 }148 private handleDuplicateBaseKeepApply(): SyncResolvedPayload[] {149 const leftPayloads = PayloadsByDuplicating({150 payload: this.basePayload,151 baseCollection: this.baseCollection,152 isConflict: true,153 source: this.applyPayload.source,154 })155 const rightPayload = this.applyPayload.copyAsSyncResolved(156 {157 lastSyncBegan: this.basePayload.lastSyncBegan,158 dirty: false,159 lastSyncEnd: new Date(),160 },161 this.applyPayload.source,162 )163 return leftPayloads.concat([rightPayload])164 }165 private handleKeepBaseMergeRefsStrategy(): SyncResolvedPayload[] {166 if (!isDecryptedPayload(this.basePayload) || !isDecryptedPayload(this.applyPayload)) {167 return []168 }169 const refs = uniqCombineObjArrays(this.basePayload.content.references, this.applyPayload.content.references, [170 'uuid',171 'content_type',172 ])173 const updatedAt = greaterOfTwoDates(this.basePayload.serverUpdatedAt, this.applyPayload.serverUpdatedAt)174 const updatedAtTimestamp = Math.max(this.basePayload.updated_at_timestamp, this.applyPayload.updated_at_timestamp)175 const payload = this.basePayload.copyAsSyncResolved(176 {177 updated_at: updatedAt,178 updated_at_timestamp: updatedAtTimestamp,179 dirty: true,180 dirtyIndex: getIncrementedDirtyIndex(),181 lastSyncEnd: new Date(),182 content: {183 ...this.basePayload.content,184 references: refs,185 },186 },187 this.applyPayload.source,188 )189 return [payload]190 }...

Full Screen

Full Screen

Conflict.spec.ts

Source:Conflict.spec.ts Github

copy

Full Screen

1import { ContentType } from '@standardnotes/common'2import { FillItemContent } from '../../Abstract/Content/ItemContent'3import { ConflictStrategy } from '../../Abstract/Item'4import {5 DecryptedPayload,6 EncryptedPayload,7 FullyFormedPayloadInterface,8 PayloadTimestampDefaults,9} from '../../Abstract/Payload'10import { ItemsKeyContent } from '../../Syncable/ItemsKey/ItemsKeyInterface'11import { ImmutablePayloadCollection } from '../Collection/Payload/ImmutablePayloadCollection'12import { PayloadCollection } from '../Collection/Payload/PayloadCollection'13import { HistoryMap } from '../History'14import { ConflictDelta } from './Conflict'15describe('conflict delta', () => {16 const historyMap = {} as HistoryMap17 const createBaseCollection = (payload: FullyFormedPayloadInterface) => {18 const baseCollection = new PayloadCollection()19 baseCollection.set(payload)20 return ImmutablePayloadCollection.FromCollection(baseCollection)21 }22 const createDecryptedItemsKey = (uuid: string, key: string, timestamp = 0) => {23 return new DecryptedPayload<ItemsKeyContent>({24 uuid: uuid,25 content_type: ContentType.ItemsKey,26 content: FillItemContent<ItemsKeyContent>({27 itemsKey: key,28 }),29 ...PayloadTimestampDefaults(),30 updated_at_timestamp: timestamp,31 })32 }33 const createErroredItemsKey = (uuid: string, timestamp = 0) => {34 return new EncryptedPayload({35 uuid: uuid,36 content_type: ContentType.ItemsKey,37 content: '004:...',38 enc_item_key: '004:...',39 items_key_id: undefined,40 errorDecrypting: true,41 waitingForKey: false,42 ...PayloadTimestampDefaults(),43 updated_at_timestamp: timestamp,44 })45 }46 it('when apply is an items key, logic should be diverted to items key delta', () => {47 const basePayload = createDecryptedItemsKey('123', 'secret')48 const baseCollection = createBaseCollection(basePayload)49 const applyPayload = createDecryptedItemsKey('123', 'secret', 2)50 const delta = new ConflictDelta(baseCollection, basePayload, applyPayload, historyMap)51 const mocked = (delta.getConflictStrategy = jest.fn())52 delta.result()53 expect(mocked).toBeCalledTimes(0)54 })55 it('if apply payload is errored but base payload is not, should duplicate base and keep apply', () => {56 const basePayload = createDecryptedItemsKey('123', 'secret')57 const baseCollection = createBaseCollection(basePayload)58 const applyPayload = createErroredItemsKey('123', 2)59 const delta = new ConflictDelta(baseCollection, basePayload, applyPayload, historyMap)60 expect(delta.getConflictStrategy()).toBe(ConflictStrategy.DuplicateBaseKeepApply)61 })62 it('if base payload is errored but apply is not, should keep base duplicate apply', () => {63 const basePayload = createErroredItemsKey('123', 2)64 const baseCollection = createBaseCollection(basePayload)65 const applyPayload = createDecryptedItemsKey('123', 'secret')66 const delta = new ConflictDelta(baseCollection, basePayload, applyPayload, historyMap)67 expect(delta.getConflictStrategy()).toBe(ConflictStrategy.KeepBaseDuplicateApply)68 })69 it('if base and apply are errored, should keep apply', () => {70 const basePayload = createErroredItemsKey('123', 2)71 const baseCollection = createBaseCollection(basePayload)72 const applyPayload = createErroredItemsKey('123', 3)73 const delta = new ConflictDelta(baseCollection, basePayload, applyPayload, historyMap)74 expect(delta.getConflictStrategy()).toBe(ConflictStrategy.KeepApply)75 })...

Full Screen

Full Screen

api.reducer.ts

Source:api.reducer.ts Github

copy

Full Screen

...41 }),42 [`${reducerName}Loaded`]: (state: ApiInterface, action) => ({43 error: '',44 apiState: API_STATE.LOADED,45 data: applyPayload(action.payload, state.data),46 }),47 [`${reducerName}Error`]: (state: ApiInterface, action) => ({48 ...state,49 apiState: API_STATE.ERROR,50 error: action.payload,51 }),52 [`${reducerName}Failed`]: (state: ApiInterface, action) => ({53 ...state,54 apiState: API_STATE.FAILED,55 error: action.payload,56 }),57 },58 extraReducers,59 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { applyPayload } from 'ng-mocks';2import { createComponent } from 'ng-mocks';3import { createService } from 'ng-mocks';4import { findInstance } from 'ng-mocks';5import { findInstances } from 'ng-mocks';6import { findReadonlyInstance } from 'ng-mocks';7import { findReadonlyInstances } from 'ng-mocks';8import { findRenderedComponent } from 'ng-mocks';9import { findRenderedComponents } from 'ng-mocks';10import { findRenderedDirective } from 'ng-mocks';11import { findRenderedDirectives } from 'ng-mocks';12import { findRenderedInstance } from 'ng-mocks';13import { findRenderedInstances } from 'ng-mocks';14import { findRenderedReadonlyInstance } from 'ng-mocks';15import { findRenderedReadonlyInstances } from 'ng-mocks';16import { findRenderedTemplate } from 'ng-mocks';17import { findRenderedTemplates } from 'ng-mocks';18import { findTemplateRef } from 'ng-mocks';19import { findTemplateRefs } from 'ng-mocks';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4 beforeEach(() => MockBuilder(MyComponent));5 it('should render', () => {6 const fixture = MockRender(MyComponent);7 const component = fixture.point.componentInstance;8 .applyPayload(component, {9 })10 .subscribe(() => {11 fixture.detectChanges();12 expect(fixture.nativeElement).toMatchSnapshot();13 });14 });15});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { applyPayload } from 'ng-mocks';2@Component({3})4export class TestComponent implements OnInit {5 constructor() {}6 ngOnInit() {7 applyPayload(this, {8 });9 }10}11{{name}} {{age}}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender, MockInstance, ngMocks } from 'ng-mocks';2import { AppComponent } from './app.component';3import { AppService } from './app.service';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent).mock(AppService));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.point.componentInstance;9 expect(app).toBeTruthy();10 });11 it('should call applyPayload method of ng-mocks', () => {12 const fixture = MockRender(AppComponent);13 const app = fixture.point.componentInstance;14 ngMocks.applyPayload(AppComponent, { name: 'test' });15 expect(app.name).toEqual('test');16 });17});18import { Component, Input } from '@angular/core';19import { AppService } from './app.service';20@Component({21})22export class AppComponent {23 title = 'ng-mocks';24 @Input() name: string;25 constructor(private appService: AppService) {26 this.name = this.appService.getName();27 }28}29import { Injectable } from '@angular/core';30@Injectable({31})32export class AppService {33 getName() {34 return 'test';35 }36}37<h1>{{title}}</h1>38<h2>{{name}}</h2>39h1 {40 color: #369;41 font-family: Arial, Helvetica, sans-serif;42 font-size: 250%;43}44h2 {45 color: #444;46 font-family: Arial, Helvetica, sans-serif;47 font-size: 200%;48}49import { MockBuilder, MockRender, MockInstance, ngMocks } from 'ng-mocks';50import { AppComponent } from './app.component';51import { AppService } from './app.service';52describe('AppComponent', () => {53 beforeEach(() => MockBuilder(AppComponent).mock(AppService));54 it('should create the app', () => {55 const fixture = MockRender(AppComponent);56 const app = fixture.point.componentInstance;

Full Screen

Using AI Code Generation

copy

Full Screen

1const payload = {2 { 'name': 'Ford', 'models': ['Fiesta', 'Focus', 'Mustang'] },3 { 'name': 'BMW', 'models': ['320', 'X3', 'X5'] },4 { 'name': 'Fiat', 'models': ['500', 'Panda'] }5};6ngMocks.applyPayload(component, payload);7ngMocks.applyInput(component, 'name', 'John');8ngMocks.applyOutput(component, 'name', 'John');9ngMocks.applyProvider(component, 'name', 'John');10ngMocks.applyProvider(component, 'name', 'John');11ngMocks.applyProvider(component, 'name', 'John');12ngMocks.applyProvider(component, 'name', 'John');13ngMocks.applyProvider(component, 'name', 'John');14ngMocks.applyProvider(component, 'name', 'John');15ngMocks.applyProvider(component, 'name', 'John');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { applyPayload } = require('ng-mocks');2const { MyComponent } = require('./my.component');3const { MyModule } = require('./my.module');4describe('MyComponent', () => {5 it('should work', () => {6 const fixture = MockRender(MyComponent, MyModule);7 const component = fixture.point.componentInstance;8 applyPayload(component, {9 });10 expect(component.name).toEqual('test');11 expect(component.age).toEqual(20);12 });13});14module.exports = {15};16module.exports = function(config) {17 config.set({18 });19};20module.exports = {21};22{23 "projects": {24 "my-app": {25 "architect": {26 "build": {27 "options": {28 },29 },30 },31 },32 },33}34import 'ng-mocks';

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful