ts-mockito#instance TypeScript Examples

The following examples show how to use ts-mockito#instance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: internal.spec.ts    From kin-node with MIT License 6 votes vote down vote up
function newTestEnv(appIndex?: number): TestEnv {
    const accountClientV4 = mock(accountgrpcv4.AccountClient);
    const airdropClientV4 = mock(airdropgrpcv4.AirdropClient);
    const txClientV4 = mock(transactiongrpcv4.TransactionClient);

    return {
        'client': new InternalClient({
            accountClientV4: instance(accountClientV4),
            airdropClientV4: instance(airdropClientV4),
            txClientV4: instance(txClientV4),
            appIndex: appIndex,
        }),
        'accountClientV4': accountClientV4,
        'airdropClientV4': airdropClientV4,
        'txClientV4': txClientV4,
    };
}
Example #2
Source File: app.component.spec.ts    From canopy with Apache License 2.0 6 votes vote down vote up
describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(waitForAsync(() => {
    const formBuilderMock = mock(FormBuilder);

    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [MockModule(CanopyModule)],
      providers: [{ provide: FormBuilder, useFactory: () => instance(formBuilderMock) }],
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create the app', () => {
    expect(component).toBeTruthy();
  });

  it(`should have as title 'canopy-test-app'`, () => {
    expect(component.title).toEqual('canopy-test-app');
  });
});
Example #3
Source File: PlaybackEngine.test.ts    From osmd-audio-player with MIT License 6 votes vote down vote up
function createOsmdMock(): OpenSheetMusicDisplay {
  const mockedOsmd = mock(OpenSheetMusicDisplay);
  const mockedSheet = mock(MusicSheet);
  const mockedPlaybackSettings = mock(PlaybackSettings);
  const mockedFraction = mock(Fraction);
  const mockedCursor = mock(Cursor);

  //@ts-ignore
  when(mockedCursor.Iterator).thenReturn({ EndReached: true });
  when(mockedOsmd.cursor).thenReturn(instance(mockedCursor));
  when(mockedSheet.Instruments).thenReturn([]);
  when(mockedPlaybackSettings.rhythm).thenReturn(instance(mockedFraction));
  when(mockedSheet.SheetPlaybackSetting).thenReturn(instance(mockedPlaybackSettings));
  when(mockedOsmd.Sheet).thenReturn(instance(mockedSheet));
  return instance(mockedOsmd);
}
Example #4
Source File: client.spec.ts    From kin-node with MIT License 6 votes vote down vote up
test("submitPayment invalid", async () => {
    const internal = mock(InternalClient);
    const client = new Client(Environment.Test, {
        internal: instance(internal),
    });

    const sender = PrivateKey.random();
    const dest = PrivateKey.random();
    const payments: Payment[] = [
        {
            sender: sender,
            destination: dest.publicKey(),
            type: TransactionType.Spend,
            quarks: new BigNumber(11),
            invoice: {
                Items: [
                    {
                        title: "test",
                        amount: new BigNumber(10),
                    }
                ]
            },
        }
    ];

    for (const p of payments) {
        try {
            await client.submitPayment(p);
            fail();
        } catch (error) {
            expect(typeof error).toBe('string');
        }
    }
});
Example #5
Source File: futureDate.validator.spec.ts    From canopy with Apache License 2.0 6 votes vote down vote up
describe('futureDate', () => {
  let control: AbstractControl;
  let validator: ValidatorFn;

  beforeEach(() => {
    control = mock(AbstractControl);
    validator = futureDateValidator();
  });

  it('returns a futureDate error if the date is not in the future', () => {
    when(control.value).thenReturn(format(subDays(new Date(), 10), 'yyyy-MM-dd'));

    expect(validator(instance(control))).toEqual({
      futureDate: true,
    });
  });

  it('returns null if the date is not a valid date', () => {
    when(control.value).thenReturn(null);

    expect(validator(instance(control))).toBe(null);
  });

  it('returns null if date is in the future', () => {
    when(control.value).thenReturn(format(addDays(new Date(), 10), 'yyyy-MM-dd'));

    expect(validator(instance(control))).toBe(null);
  });
});
Example #6
Source File: mocks.ts    From xrp-api with MIT License 5 votes vote down vote up
mockedRippleApiServiceInstance = instance(mockedRippleApiService)
Example #7
Source File: modal-header.component.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgModalHeaderComponent', () => {
  let component: LgModalHeaderComponent;
  let fixture: ComponentFixture<LgModalHeaderComponent>;
  let modalServiceMock: LgModalService;

  beforeEach(async () => {
    modalServiceMock = mock(LgModalService);

    await TestBed.configureTestingModule({
      declarations: [ LgModalHeaderComponent ],
      providers: [ { provide: LgModalService, useValue: instance(modalServiceMock) } ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LgModalHeaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should have a class', () => {
    expect(fixture.nativeElement.getAttribute('class')).toContain('lg-modal-header');
  });

  it('should have an id', () => {
    component.id = 'test-2';
    fixture.detectChanges();

    expect(fixture.nativeElement.getAttribute('id')).toContain('test-2');
  });

  it('should close the modal on #close', () => {
    component.modalId = 'test';
    component.close();

    verify(modalServiceMock.close('test')).once();

    expect().nothing();
  });
});
Example #8
Source File: roles.guard.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('RolesGuard(ts-mockito)', () => {
  let guard: RolesGuard;
  const reflecter = mock(Reflector);
  beforeEach(() => {
    guard = new RolesGuard(instance(reflecter));
  });

  afterEach(() => {
    reset();
  });

  it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
    const context = mock<ExecutionContext>();
    when(context.getHandler()).thenReturn({} as any);

    const contextInstacne = instance(context);
    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([] as RoleType[]);
    const result = await guard.canActivate(contextInstacne);

    expect(result).toBeTruthy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });

  it('should return true if the `HasRoles` decorator is set', async () => {
    const context = mock<ExecutionContext>();

    when(context.getHandler()).thenReturn({} as any);

    const arguHost = mock<HttpArgumentsHost>();
    when(arguHost.getRequest()).thenReturn({
      user: { roles: [RoleType.USER] },
    } as any);

    when(context.switchToHttp()).thenReturn(instance(arguHost));
    const contextInstacne = instance(context);

    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([RoleType.USER] as RoleType[]);

    const result = await guard.canActivate(contextInstacne);
    console.log(result);
    expect(result).toBeTruthy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });

  it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
    const context = mock<ExecutionContext>();

    when(context.getHandler()).thenReturn({} as any);

    // logged in as USER
    const arguHost = mock<HttpArgumentsHost>();
    when(arguHost.getRequest()).thenReturn({
      user: { roles: [RoleType.USER] },
    } as any);

    when(context.switchToHttp()).thenReturn(instance(arguHost));
    const contextInstacne = instance(context);

    // but requires ADMIN
    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([RoleType.ADMIN] as RoleType[]);

    const result = await guard.canActivate(contextInstacne);
    console.log(result);
    expect(result).toBeFalsy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });
});
Example #9
Source File: client.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test("client account management", async () => {
    const internal = mock(InternalClient);

    const accountBalances = new Map<string, BigNumber>();
    when(internal.createAccount(anything(), anything(), anything()))
        .thenCall((account: PrivateKey) => {
            if (accountBalances.has(account.publicKey().toBase58())) {
                throw new AccountExists();
            }

            return Promise.resolve(accountBalances.set(account.publicKey().toBase58(), new BigNumber(10)));
        });
    when(internal.getAccountInfo(anything(), anything()))
        .thenCall((account: PublicKey) => {
            const balance = accountBalances.get(account.toBase58());
            if (!balance) {
                throw new AccountDoesNotExist();
            }

            const account_info = new accountpbv4.AccountInfo();
            account_info.setBalance(balance.toString());
            return Promise.resolve(account_info);
        });


    const account = PrivateKey.random();
    const client = new Client(Environment.Test, {
        appIndex: 0,
        internal: instance(internal),
    });

    await client.createAccount(account);

    try {
        await client.createAccount(account);
        fail();
    } catch (err) {
        expect(err).toBeInstanceOf(AccountExists);
    }

    expect(await client.getBalance(account.publicKey())).toStrictEqual(new BigNumber(10));
});
Example #10
Source File: mocks.ts    From xrp-api with MIT License 5 votes vote down vote up
debuglogInstance = instance(mockedDebuglog)
Example #11
Source File: toggle.component.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgToggleComponent selector variant', () => {
  let fixture: ComponentFixture<TestToggleVariantSelectorComponent>;
  let toggleDebugElement: DebugElement;
  let toggleInstance: LgToggleComponent;
  let inputLabelElement: DebugElement;

  const errorStateMatcherMock = mock(LgErrorStateMatcher);

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [ FormsModule, ReactiveFormsModule ],
        declarations: [
          TestToggleVariantSelectorComponent,
          LgToggleComponent,
          MockComponents(LgValidationComponent, LgIconComponent),
        ],
        providers: [
          {
            provide: LgErrorStateMatcher,
            useFactory: () => instance(errorStateMatcherMock),
          },
        ],
      }).compileComponents();

      fixture = TestBed.createComponent(TestToggleVariantSelectorComponent);
      fixture.detectChanges();

      toggleDebugElement = fixture.debugElement.query(By.directive(LgToggleComponent));

      toggleInstance =
        toggleDebugElement.injector.get<LgToggleComponent>(LgToggleComponent);

      inputLabelElement = fixture.debugElement.query(By.css('.lg-toggle__label'));
      fixture.detectChanges();
    }),
  );

  it('sets the correct variant based on the selector', () => {
    expect(toggleInstance.variant).toBe('switch');
  });

  it('sets the correct modifier class based on the variant', () => {
    expect(
      inputLabelElement.nativeElement.classList.contains('lg-toggle__label--filter'),
    ).toBe(false);

    expect(
      inputLabelElement.nativeElement.classList.contains('lg-toggle__label--switch'),
    ).toBe(true);
  });
});
Example #12
Source File: users.spec.ts    From space-sdk with MIT License 5 votes vote down vote up
describe('Users...', () => {
  const config: UsersConfig = {
    endpoint: '',
    authChallengeSolver: async () => ({
      token: 'app-token',
      storageAuth: {
        key: '',
        token: 'mock-auth-token',
        sig: '',
        msg: '',
      },
    }),
  };

  describe('identity', () => {
    const users = new Users(config);

    it('create and authenticate', async () => {
      const identity = await users.createIdentity();
      const user = await users.authenticate(identity);

      expect(user.token).to.equal('app-token');
    });
  });

  describe('recoverKeysByPassPhrase', () => {
    it('should throw if vaultInit or vaultServiceConfig are missing', async () => {
      const users = new Users(config);
      await expect(users.recoverKeysByPassphrase('', '', VaultBackupType.Twitter)).to.eventually.be.rejected;
    });

    // it('should add new identity to identity storage', async () => {});
  });

  describe('backupKeysByPassphrase', () => {
    it('should throw if vaultInit or vaultServiceConfig is missing', async () => {
      const users = new Users(config);
      const mockIdentity: PrivateKey = mock();

      await expect(
        users.backupKeysByPassphrase('', '', VaultBackupType.Twitter, instance(mockIdentity)),
      ).to.eventually.be.rejectedWith('Either vaultServiceConfig or vaultInit configuration is required.');
    });

    it('should throw if identity provided is not a private key', async () => {
      const users = new Users(config);
      const mockIdentity: PrivateKey = mock();
      when(mockIdentity.privKey).thenReturn((null as unknown) as Uint8Array);

      await expect(
        users.backupKeysByPassphrase('', '', VaultBackupType.Twitter, instance(mockIdentity)),
      ).to.eventually.be.rejectedWith('identity provided is not a valid PrivateKey Identity.');
    });
  });
});
Example #13
Source File: web3-provider.connector.test.ts    From limit-order-protocol-utils with MIT License 5 votes vote down vote up
describe('Web3ProviderConnector', () => {
    let web3Provider: Web3;
    let web3ProviderConnector: Web3ProviderConnector;

    const typedData = {
        primaryType: 'Order',
        types: {
            EIP712Domain: EIP712_DOMAIN,
            Order: ORDER_STRUCTURE,
        },
        domain: {
            name: PROTOCOL_NAME,
            version: PROTOCOL_VERSION,
            chainId: 1,
            verifyingContract: '',
        },
        message: {},
    };

    beforeEach(() => {
        web3Provider = mock<Web3>();
        web3ProviderConnector = new Web3ProviderConnector(
            instance(web3Provider)
        );
    });

    it('signTypedData() must call eth_signTypedData_v4 rpc method', async () => {
        const walletAddress = '0xasd';

        const extendedWeb3 = {
            signTypedDataV4: jest.fn(),
        };

        when(web3Provider.extend(anything())).thenReturn(extendedWeb3);

        await web3ProviderConnector.signTypedData(walletAddress, typedData, '');

        expect(extendedWeb3.signTypedDataV4).toHaveBeenCalledWith(
            walletAddress,
            JSON.stringify(typedData)
        );
    });

    it('contractEncodeABI() changed address from null to undefined for contract instance', async () => {
        const eth = mock<Eth>();
        class ContractMock {
            methods = {
                foo: () => ({encodeABI: () => ''}),
            };
        }

        /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
        when(eth.Contract).thenReturn(ContractMock as any);
        when(web3Provider.eth).thenReturn(instance(eth));

        web3ProviderConnector.contractEncodeABI(
            LIMIT_ORDER_PROTOCOL_ABI,
            null,
            'foo',
            []
        );

        verify(eth.Contract).once();
    });
});
Example #14
Source File: error-state-matcher.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgErrorStateMatcher', () => {
  let service: LgErrorStateMatcher;
  let control: NgControl;
  let controlContainer: FormGroupDirective;

  beforeEach(() => {
    service = new LgErrorStateMatcher();
    control = mock(NgControl);
    controlContainer = mock(FormGroupDirective);
  });

  describe('isControlInvalid', () => {
    describe('invalid states', () => {
      it('control is invalid, touched and dirty', () => {
        when(control.invalid).thenReturn(true);
        when(control.touched).thenReturn(true);
        when(control.dirty).thenReturn(true);

        expect(service.isControlInvalid(instance(control))).toBe(true);
      });

      it('control is invalid and untouched and form is submitted', () => {
        when(control.invalid).thenReturn(true);
        when(control.touched).thenReturn(false);
        when(controlContainer.submitted).thenReturn(true);

        expect(
          service.isControlInvalid(instance(control), instance(controlContainer)),
        ).toBe(true);
      });
    });

    describe('pending states', () => {
      it('control is invalid and not touched', () => {
        when(control.invalid).thenReturn(true);
        when(control.touched).thenReturn(false);
        when(control.dirty).thenReturn(false);

        expect(service.isControlInvalid(instance(control))).toBe(false);
      });

      it('control is not invalid and not touched', () => {
        when(control.invalid).thenReturn(false);
        when(control.touched).thenReturn(false);
        when(control.dirty).thenReturn(false);

        expect(service.isControlInvalid(instance(control))).toBe(false);
      });

      it('control is valid and touched', () => {
        when(control.invalid).thenReturn(false);
        when(control.touched).thenReturn(true);
        when(control.dirty).thenReturn(true);

        expect(service.isControlInvalid(instance(control))).toBe(false);
      });

      it('control is valid and untouched and form is submitted', () => {
        when(control.invalid).thenReturn(false);
        when(control.touched).thenReturn(false);
        when(control.dirty).thenReturn(false);
        when(controlContainer.submitted).thenReturn(true);

        expect(
          service.isControlInvalid(instance(control), instance(controlContainer)),
        ).toBe(false);
      });
    });
  });
});
Example #15
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitEarnBatch", async() => {
    const sender = PrivateKey.random();

    const expectedDestinations: PublicKey[] = [];
    const earns = new Array<Earn>();
    for (let i = 0; i < 15; i++) {
        const dest = PrivateKey.random();
        earns.push({
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
        });
        expectedDestinations.push(dest.publicKey());
    }
    const invoiceEarns = new Array<Earn>();
    for (let i = 0; i < 15; i++) {
        const dest = PrivateKey.random();
        invoiceEarns.push({
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
            invoice: {
                Items: [
                    {
                        title: "test",
                        amount: new BigNumber(i + 1),
                    }
                ]
            },
        });
    }

    const batches: EarnBatch[] = [
        {
            sender: sender,
            earns: earns,
            dedupeId: Buffer.from(uuidv4())
        },
        {
            sender: sender,
            earns: earns,
            memo: "somememo",
        },
        {
            sender: sender,
            earns: invoiceEarns,
        },
    ];
    
    let signReq: signRequest | undefined;
    let submitReq: submitRequest | undefined;

    const internal = mock(InternalClient);
    when(internal.signTransaction(anything(), anything()))
        .thenCall((tx: Transaction, il?: commonpb.InvoiceList) => {
            // Make a copy of the transaction since we're modifying it

            signReq = {tx: Transaction.from(tx.serialize({
                requireAllSignatures: false,
                verifySignatures: false,
            })), il};

            const result = new SignTransactionResult();
            if (tx.feePayer!.toBuffer().equals(subsidizer)){
                tx.partialSign(new Account(subsidizerKey.secretKey()));
            }
            result.TxId = tx.signature ? tx.signature : undefined;
            return Promise.resolve(result);
        });
    
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
    .thenCall((tx: Transaction, il?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            submitReq = {tx, il, commitment, dedupeId};

            const result = new SubmitTransactionResult();
            result.TxId = tx.signature!;

            return Promise.resolve(result);
        });

    setGetServiceConfigResp(internal);
    setGetRecentBlockhashResp(internal);    

    const client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });

    for (const b of batches) {
        signReq = undefined;
        submitReq = undefined;

        const result = await client.submitEarnBatch(b);
        expect(result.txId.length).toEqual(64);
        expect(result.txId.equals(Buffer.alloc(64).fill(0))).toBeFalsy();
        expect(result.txError).toBeUndefined();
        expect(result.earnErrors).toBeUndefined();

        expect(signReq).toBeDefined();

        const signTx = signReq!.tx;
        expect(signTx.signatures).toHaveLength(2);
        expect(signTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
        expect(signTx.signatures[0].signature).toBeNull();
        expect(signTx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(signTx.serializeMessage(), signTx.signatures[1].signature!)).toBeTruthy();

        const memoInstruction = MemoInstruction.decodeMemo(signTx.instructions[0]);
        
        if (b.memo) { 
            expect(memoInstruction.data).toEqual(b.memo);
        } else if (b.earns[0].invoice) {
            const serialized = submitReq!.il!.serializeBinary();
            const buf = Buffer.from(hash.sha224().update(serialized).digest('hex'), "hex");
            const expected = Memo.new(1, TransactionType.Earn, 1, buf);
            
            expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        } else {
            // since we have an app index configured, we still expect a memo
            const expected = Memo.new(1, TransactionType.Earn, 1, Buffer.alloc(29));
            expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        }
        
        expect(signTx.instructions).toHaveLength(16);  // including memo

        for (let i = 0; i < 15; i++) {
            const tokenInstruction = TokenInstruction.decodeTransfer(signTx.instructions[i + 1]);    
            expect(tokenInstruction.source.toBuffer()).toEqual(sender.publicKey().buffer);

            expect(tokenInstruction.dest.toBuffer()).toEqual(b.earns[i].destination.buffer);
            expect(tokenInstruction.owner.toBuffer()).toEqual(sender.publicKey().buffer);
            expect(tokenInstruction.amount).toEqual(BigInt((i + 1)));
        }
        
        expect(submitReq).toBeDefined();
        expect(submitReq!.dedupeId).toEqual(b.dedupeId);
        
        const submitTx = submitReq!.tx;
        expect(submitTx.signatures).toHaveLength(2);
        expect(submitTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
        expect(subsidizerKey.kp.verify(submitTx.serializeMessage(), submitTx.signatures[0].signature!)).toBeTruthy();
        expect(submitTx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();

        expect(submitTx.serializeMessage()).toEqual(signTx.serializeMessage());
    }
});
Example #16
Source File: private-key-provider.connector.test.ts    From limit-order-protocol-utils with MIT License 4 votes vote down vote up
describe('PrivateKeyProviderConnector', () => {
    let web3Provider: Web3;
    let privateKeyProviderConnector: PrivateKeyProviderConnector;

    const testPrivateKey =
        'd8d1f95deb28949ea0ecc4e9a0decf89e98422c2d76ab6e5f736792a388c56c7';
    const limitOrder: LimitOrder = {
        salt: '1469462901577',
        getMakerAmount:
            '0xf4a215c30000000000000000000000000000000000000000000000',
        getTakerAmount:
            '0x296637bf0000000000000000000000000000000000000000000000',
        makerAsset: '0x111111111117dc0aa78b770fa6a738034120c302',
        takerAsset: '0xe9e7cea3dedca5984780bafc599bd69add087d56',
        maker: '0xa07c1d51497fb6e66aa2329cecb86fca0a957fdb',
        receiver: '0x0000000000000000000000000000000000000000',
        allowedSender: '0x0000000000000000000000000000000000000000',
        makingAmount: '1000000000000000000000',
        takingAmount: '90000000000000000000',
        makerAssetData:
            '0x23b872dd000000000000000000000000fb3c7eb936caa12b5a884d612393969a557d43070000',
        takerAssetData:
            '0x23b872dd00000000000000000000000000000000000000000000000000000000000000000000',
        interaction: '0x',
        permit: '0x',
        predicate: '0x',
    };
    const typedData: EIP712TypedData = {
        primaryType: 'Order',
        types: {
            EIP712Domain: EIP712_DOMAIN,
            Order: ORDER_STRUCTURE,
        },
        domain: {
            name: PROTOCOL_NAME,
            version: PROTOCOL_VERSION,
            chainId: 1,
            verifyingContract: '',
        },
        message: limitOrder,
    };

    beforeEach(() => {
        web3Provider = mock<Web3>();
        privateKeyProviderConnector = new PrivateKeyProviderConnector(
            testPrivateKey,
            instance(web3Provider)
        );
    });

    it('signTypedData() must sign typed data by private key', async () => {
        const walletAddress = '0xa07c1d51497fb6e66aa2329cecb86fca0a957fdb';

        const signature = await privateKeyProviderConnector.signTypedData(
            walletAddress,
            typedData
        );

        expect(signature).toMatchSnapshot();
    });

    it('contractEncodeABI() changed address from null to undefined for contract instance', async () => {
        const eth = mock<Eth>();
        class ContractMock {
            methods = {
                foo: () => ({encodeABI: () => ''}),
            };
        }

        /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
        when(eth.Contract).thenReturn(ContractMock as any);
        when(web3Provider.eth).thenReturn(instance(eth));

        privateKeyProviderConnector.contractEncodeABI(
            LIMIT_ORDER_PROTOCOL_ABI,
            null,
            'foo',
            []
        );

        verify(eth.Contract).once();
    });
});
Example #17
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitPayment with preferred account resolution", async() => {
    const internal = mock(InternalClient);

    interface submitRequest {
        tx: Transaction,
        invoice?: commonpb.InvoiceList,
        commitment?: Commitment,
        dedupeId?: Buffer,
    }
    const requests: submitRequest[] = [];
    
    let attemptedSubmission = false;
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall((tx: Transaction, invoice?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            requests.push({tx, invoice, commitment, dedupeId});
            
            const result = new SubmitTransactionResult();
            result.TxId = tx.signature!;
            if (!attemptedSubmission) {
                attemptedSubmission = true;
            
                const errors = new TransactionErrors();
                errors.TxError = new AccountDoesNotExist();
                result.Errors = errors;
            }
            return Promise.resolve(result);
        });
    
    const appSubsidizer = PrivateKey.random();
    const sender = PrivateKey.random();
    const dest = PrivateKey.random();
    const resolvedSender = PrivateKey.random();
    const resolvedDest = PrivateKey.random();
    const resolvedAccounts = new Map<string, PublicKey>([
        [sender.publicKey().toBase58(), resolvedSender.publicKey()],
        [dest.publicKey().toBase58(), resolvedDest.publicKey()],
    ]);
    
    when(internal.resolveTokenAccounts(anything(), anything()))
        .thenCall((key: PublicKey) => {
            const resolvedAccount = resolvedAccounts.get(key.toBase58());

            if (resolvedAccount) {
                const id = new commonpbv4.SolanaAccountId();
                id.setValue(resolvedAccount.buffer);
    
                const info = new accountpbv4.AccountInfo();
                info.setAccountId(id);
                return Promise.resolve([info]);
            }

            return Promise.resolve([]);
        });
    
    setGetServiceConfigResp(internal);
    setGetRecentBlockhashResp(internal);

    const p: Payment = {
        sender: sender,
        destination: dest.publicKey(),
        type: TransactionType.Spend,
        quarks: new BigNumber(11),
        subsidizer: appSubsidizer,
    };

    const client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });

    let txId = await client.submitPayment(p);
    expect(txId.length).toEqual(64);
    expect(txId.equals(Buffer.alloc(64).fill(0))).toBeFalsy();
    expect(requests).toHaveLength(2);

    const resolved = [false, true];
    requests.forEach((request, i) => {
        expect(request).toBeDefined();

        const tx = request!.tx;
        expect(tx.signatures).toHaveLength(2);
        expect(tx.signatures[0].publicKey.toBuffer()).toEqual(appSubsidizer.publicKey().buffer);
        expect(appSubsidizer.kp.verify(tx.serializeMessage(), tx.signatures[0].signature!)).toBeTruthy();

        expect(tx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(tx.serializeMessage(), tx.signatures[1].signature!)).toBeTruthy();

        expect(tx.instructions).toHaveLength(2);
        
        const memoInstruction = MemoInstruction.decodeMemo(tx.instructions[0]);
        
        const expected = Memo.new(1, p.type, 1, Buffer.alloc(29));
        expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        
        const tokenInstruction = TokenInstruction.decodeTransfer(tx.instructions[1]);
        
        if (resolved[i]) {
            expect(tokenInstruction.source.toBuffer()).toEqual(resolvedSender.publicKey().buffer);
            expect(tokenInstruction.dest.toBuffer()).toEqual(resolvedDest.publicKey().buffer);
        } else {
            expect(tokenInstruction.source.toBuffer()).toEqual(sender.publicKey().buffer);
            expect(tokenInstruction.dest.toBuffer()).toEqual(dest.publicKey().buffer);
        }
        expect(tokenInstruction.owner.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(tokenInstruction.amount).toEqual(BigInt(p.quarks));
    });

    txId = await client.submitPayment(p);
    expect(txId.length).toEqual(64);
    expect(txId.equals(Buffer.alloc(64).fill(0))).toBeFalsy();
    expect(requests).toHaveLength(3);
});
Example #18
Source File: checkbox-group.component.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgCheckboxGroupComponent', () => {
  let fixture: ComponentFixture<TestCheckboxGroupComponent>;
  let groupDebugElement: DebugElement;
  let errorDebugElement: DebugElement;
  let hintDebugElement: DebugElement;
  let fieldsetDebugElement: DebugElement;
  let checkboxDebugElements: Array<DebugElement>;

  let groupInstance: LgCheckboxGroupComponent;
  let checkboxInstances: Array<LgToggleComponent>;
  let component: TestCheckboxGroupComponent;
  let errorStateMatcherMock: LgErrorStateMatcher;

  beforeEach(waitForAsync(() => {
    errorStateMatcherMock = mock(LgErrorStateMatcher);

    TestBed.configureTestingModule({
      imports: [ FormsModule, ReactiveFormsModule ],
      declarations: [
        TestCheckboxGroupComponent,
        LgCheckboxGroupComponent,
        LgToggleComponent,
        MockComponents(LgValidationComponent, LgHintComponent, LgIconComponent),
      ],
      providers: [
        {
          provide: LgErrorStateMatcher,
          useFactory: () => instance(errorStateMatcherMock),
        },
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(TestCheckboxGroupComponent);
    component = fixture.componentInstance;

    groupDebugElement = fixture.debugElement.query(
      By.directive(LgCheckboxGroupComponent),
    );

    groupInstance = groupDebugElement.injector.get<LgCheckboxGroupComponent>(
      LgCheckboxGroupComponent,
    );

    hintDebugElement = fixture.debugElement.query(By.directive(LgHintComponent));

    fieldsetDebugElement = fixture.debugElement.query(By.css('fieldset'));

    checkboxDebugElements = fixture.debugElement.queryAll(By.css('lg-toggle'));

    checkboxInstances = checkboxDebugElements.map(debugEl => debugEl.componentInstance);

    fixture.detectChanges();
  }));

  it('sets the correct variant based on the selector', () => {
    fixture.detectChanges();

    expect(groupInstance.variant === 'filter').toBe(true);
  });

  it('sets the correct style variant on the toggle button based on the selector', () => {
    expect(fixture.debugElement.query(By.css('label')).nativeElement).toHaveClass(
      'lg-toggle__label--filter',
    );
  });

  it('adds the tabindex attribute to the fieldset element', () => {
    expect(fieldsetDebugElement.nativeElement.getAttribute('tabindex')).toBeNull();

    groupInstance.focus = true;
    fixture.detectChanges();

    expect(fieldsetDebugElement.nativeElement.getAttribute('tabindex')).toBe('-1');
  });

  it('sets all checkbox buttons to the same name', () => {
    expect(groupInstance.name.length > 0).toBe(true);
    const name = checkboxInstances.pop().name;

    for (const checkbox of checkboxInstances) {
      expect(checkbox.name).toBe(name);
    }
  });

  it('checks the selected checkbox button when a value is provided', () => {
    groupInstance.value = [ 'red' ];
    fixture.detectChanges();
    const checkedOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.checked === true,
    );

    expect(checkedOption.componentInstance.value).toContain('red');
  });

  it('unchecks the selected checkbox buttons when an empty array value is provided', () => {
    groupInstance.value = [ 'red' ];
    fixture.detectChanges();
    groupInstance.value = [];
    fixture.detectChanges();
    const checkedOptions: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.checked === true,
    );

    expect(checkedOptions).not.toBeDefined();
  });

  it('uses same unique id when setting the group id and the group name', () => {
    const checkboxGroupNextUniqueId = groupInstance['nextUniqueId'];
    const checkboxGroupId = groupInstance.id;
    const checkboxGroupName = groupInstance.name;

    expect(checkboxGroupId).toBe(`lg-checkbox-group-id-${checkboxGroupNextUniqueId}`);
    expect(checkboxGroupName).toBe(`lg-checkbox-group-${checkboxGroupNextUniqueId}`);
  });

  it('sets unique ids on all the checkbox buttons', () => {
    const checkboxIds = checkboxInstances.map(({ id }) => id);

    expect(new Set(checkboxIds).size).toBe(checkboxIds.length);

    for (const id of checkboxIds) {
      expect(/lg-toggle-\d{1,3}/.test(id)).toBe(true);
    }
  });

  it('marks the selected checkbox when the value is changed', () => {
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();
    const selected = checkboxInstances.find(checkbox => checkbox.value === 'red');

    expect(selected.checked).toBe(true);
    const notSelected = checkboxInstances.filter(checkbox => checkbox.value !== 'red');

    for (const checkbox of notSelected) {
      expect(checkbox.checked).toBe(false);
    }
  });

  it('updates the model value when a checkbox option is checked', () => {
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(component.form.controls.color.value).toContain('red');
  });

  it('updates the model value when multiple checkbox options are selected', () => {
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );
    const blueOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'blue',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    blueOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(component.form.controls.color.value.length).toBe(2);
    expect(component.form.controls.color.value).toContain('red');
    expect(component.form.controls.color.value).toContain('blue');
  });

  it('updates the model value when selected checkbox options are unselected', () => {
    groupInstance.value = [ 'red', 'blue' ];
    fixture.detectChanges();

    expect(component.form.controls.color.value.length).toBe(2);
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );
    const blueOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'blue',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    blueOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(component.form.controls.color.value.length).toBe(0);
  });

  it('links the hint to the fieldset with the correct aria attributes', () => {
    expect(hintDebugElement.nativeElement.getAttribute('id').length).not.toEqual(0);

    expect(fieldsetDebugElement.nativeElement.getAttribute('aria-describedBy')).toContain(
      hintDebugElement.nativeElement.getAttribute('id'),
    );
  });

  it('links the error to the fieldset with the correct aria attributes', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();
    errorDebugElement = fixture.debugElement.query(By.directive(LgValidationComponent));

    expect(errorDebugElement.nativeElement.getAttribute('id').length).not.toEqual(0);

    expect(fieldsetDebugElement.nativeElement.getAttribute('aria-describedBy')).toContain(
      errorDebugElement.nativeElement.getAttribute('id'),
    );
  });

  it('combines both the hint and error ids to create the aria described attribute', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();
    errorDebugElement = fixture.debugElement.query(By.directive(LgValidationComponent));

    const errorId = errorDebugElement.nativeElement.getAttribute('id');
    const hintId = hintDebugElement.nativeElement.getAttribute('id');

    fixture.detectChanges();

    expect(fieldsetDebugElement.nativeElement.getAttribute('aria-describedby')).toBe(
      `${hintId} ${errorId}`,
    );
  });

  it('disables the options when the disabled property is set', () => {
    component.form.controls.color.disable();
    fixture.detectChanges();

    for (const checkbox of checkboxInstances) {
      expect(checkbox.disabled).toBe(true);
    }
  });

  it('adds the error class if the form field is invalid', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();

    expect(groupDebugElement.nativeElement.className).toContain(
      'lg-checkbox-group--error',
    );
  });

  it('removes the error class if the form field is valid', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(
      false,
    );

    fixture.detectChanges();

    expect(groupDebugElement.nativeElement.className).not.toContain(
      'lg-checkbox-group--error',
    );
  });
});
Example #19
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitPayment submit errors", async() => {
    const internal = mock(InternalClient);

    const sender = PrivateKey.random();
    const dest = PrivateKey.random();
    const payment: Payment = {
        sender: sender,
        destination: dest.publicKey(),
        type: TransactionType.Spend,
        quarks: new BigNumber(11),
        invoice: {
            Items: [
                {
                    title: "test",
                    amount: new BigNumber(11),
                }
            ]
        }
    };

    let reason = 1;
    when(internal.signTransaction(anything(), anything()))
        .thenCall((tx: Transaction) => {
            const result = new SignTransactionResult();
            if (tx.feePayer!.toBuffer().equals(subsidizer)){
                tx.partialSign(new Account(subsidizerKey.secretKey()));
            }
            result.TxId = tx.signature ? tx.signature : undefined;
            return Promise.resolve(result);
        });
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall(() => {
            const invoiceError = new commonpb.InvoiceError();
            invoiceError.setOpIndex(0);
            invoiceError.setReason(reason);
            invoiceError.setInvoice(invoiceToProto(payment.invoice!));

            const result: SubmitTransactionResult = {
                TxId: Buffer.alloc(32),
                InvoiceErrors: [
                    invoiceError,
                ],
            };

            reason = (reason % 3) + 1;
            return Promise.resolve(result);
        });
    
    setGetServiceConfigResp(internal);
    setGetRecentBlockhashResp(internal);

    const client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });
    for (let i = 1; i <= 3; i++) {
        try {
            await client.submitPayment(payment);
            fail();
        } catch (err) {
            switch (i) {
                case commonpb.InvoiceError.Reason.ALREADY_PAID:
                    expect(err).toBeInstanceOf(AlreadyPaid);
                    break;
                case commonpb.InvoiceError.Reason.WRONG_DESTINATION:
                    expect(err).toBeInstanceOf(WrongDestination);
                    break;
                case commonpb.InvoiceError.Reason.SKU_NOT_FOUND:
                    expect(err).toBeInstanceOf(SkuNotFound);
                    break;
                default:
                    fail();
            }
        }
    }

    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall(() => {
            return Promise.resolve({
                TxId: Buffer.alloc(32),
                Errors: {
                    TxError: new InvalidSignature(),
                }
            });
        });

    try{
        await client.submitPayment(payment);
        fail();
    } catch (err) {
        expect(err).toBeInstanceOf(InvalidSignature);
    }

    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall(() => {
            return Promise.resolve({
                TxId: Buffer.alloc(32),
                Errors: {
                    TxError: new TransactionFailed(),
                    OpErrors: [
                        new InsufficientBalance(),
                    ],
                    PaymentErrors: [
                        new InsufficientBalance(),
                    ],
                }
            });
        });

    try{
        await client.submitPayment(payment);
        fail();
    } catch (err) {
        expect(err).toBeInstanceOf(InsufficientBalance);
    }
});
Example #20
Source File: multicall.service.test.ts    From multicall with MIT License 4 votes vote down vote up
describe('MultiCallService', () => {
    const multiCallAddress = '0x001';

    let multiCallService: MultiCallService;
    let connector: ProviderConnector;

    beforeEach(() => {
        connector = mock<ProviderConnector>();
        multiCallService = new MultiCallService(
            instance(connector),
            multiCallAddress
        );
    });

    beforeEach(() => {
        when(connector.contractEncodeABI(anything(), anything(), anything(), anything())).thenCall((
            _: unknown, __: string, methodName: string, params: unknown[],
        ) => {
            return {methodName, params};
        });

        when(connector.ethCall(anything(), anything(), anything())).thenCall((
            _: unknown, callData: {methodName: string, params: unknown[]}
        ) => {
            return callData;
        });
    });


    describe('callByGasLimit() full successful multicall', () => {
        beforeEach(() => {
            when(connector.decodeABIParameterList(anything(), anything())).thenCall((
                _: unknown, callData: {methodName: string, params: unknown[]}
            ) => {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                return {results: callData.params[0], lastSuccessIndex: callData.params[0].length};
            });
        });

        it('test', async () => {
            const gasLimit = 410;
            const requests: MultiCallRequestWithGas[] = [
                {to: '01', data: '01', gas: 100},
                {to: '02', data: '02', gas: 100},
                {to: '03', data: '03', gas: 100},
                {to: '04', data: '04', gas: 100},
                {to: '05', data: '05', gas: 100},
                {to: '06', data: '06', gas: 100},
                {to: '07', data: '07', gas: 100},
                {to: '08', data: '08', gas: 100},
                {to: '09', data: '09', gas: 100},
                {to: '10', data: '10', gas: 100},
            ];

            const result = await multiCallService.callByGasLimit(requests, gasLimit, {
                ...defaultParamsWithGas,
                maxChunkSize: 3,
            });

            expect(result).toEqual(requests.map(r => ({to: r.to, data: r.data})));
        });
    });

    describe('callByGasLimit() multicall with errors', () => {
        function getLastSuccessIndex(requests: MultiCallRequest[]): number {
            // lastSuccessIndex = 1, it means that only 01, 02 responses were successful
            if (requests.map(i => i.data).join('') === '010203') {
                return 1;
            }

            // lastSuccessIndex = 1, it means that only 04, 05 responses were successful
            if (requests.map(i => i.data).join('') === '040506') {
                return 1;
            }

            // lastSuccessIndex = 0, it means that only 7 responses were successful
            if (requests.map(i => i.data).join('') === '070809') {
                return 0;
            }

            return requests.length - 1;
        }

        beforeEach(() => {
            when(connector.decodeABIParameterList(anything(), anything())).thenCall((
                _: unknown, callData: {methodName: string, params: unknown[]}
            ) => {
                const results = callData.params[0] as MultiCallRequest[];

                return {results, lastSuccessIndex: getLastSuccessIndex(results)};
            });
        });

        it('test', async () => {
            const gasLimit = 300;
            const requests: MultiCallRequestWithGas[] = [
                {to: '01', data: '01', gas: 100},
                {to: '02', data: '02', gas: 100},
                {to: '03', data: '03', gas: 100},
                {to: '04', data: '04', gas: 100},
                {to: '05', data: '05', gas: 100},
                {to: '06', data: '06', gas: 100},
                {to: '07', data: '07', gas: 100},
                {to: '08', data: '08', gas: 100},
                {to: '09', data: '09', gas: 100},
                {to: '10', data: '10', gas: 100},
            ];
            const expectedRequestsByChunks = [
                [
                    {to: '01', data: '01'},
                    {to: '02', data: '02'},
                    {to: '03', data: '03'},
                ],
                [
                    {to: '04', data: '04'},
                    {to: '05', data: '05'},
                    {to: '06', data: '06'},
                ],
                [
                    {to: '07', data: '07'},
                    {to: '08', data: '08'},
                    {to: '09', data: '09'},
                ],
                [
                    {to: '10', data: '10'},
                ],
                [
                    {to: '03', data: '03'},
                    {to: '06', data: '06'},
                ],
                [
                    {to: '08', data: '08'},
                    {to: '09', data: '09'},
                ],
            ];

            const result = await multiCallService.callByGasLimit(requests, gasLimit, {
                ...defaultParamsWithGas,
                maxChunkSize: 3,
            });

            const ethCalls = capture(connector.ethCall);

            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            const ethCallArguments = [0,1,2,3,4,5].map(index => ethCalls.byCallIndex(index)[1]['params'][0]);

            expect(ethCallArguments).toEqual(expectedRequestsByChunks);
            expect(result).toEqual(requests.map(r => ({to: r.to, data: r.data})));
        });
    });
});
Example #21
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitEarnBatch with no service subsidizer", async() => {
    const internal = mock(InternalClient);

    const sender = PrivateKey.random();
    const appSubsidizer = PrivateKey.random();
    const earnCount = 10;
    const earns = new Array<Earn>(earnCount);
    for (let i = 0; i < earnCount; i++) {
        const dest = PrivateKey.random();
        earns[i] = {
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
        };
    }

    interface submitRequest {
        tx: Transaction,
        invoiceList?: commonpb.InvoiceList,
        commitment?: Commitment,
        dedupeId?: Buffer,
    }
    let request: submitRequest | undefined;

    const txId = Buffer.from("someid");
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall((tx: Transaction, invoice?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            request = {tx, invoiceList: invoice, commitment, dedupeId};

            return Promise.resolve({
                TxId: txId,
            });
        });

    setGetServiceConfigRespNoSubsidizer(internal);
    setGetRecentBlockhashResp(internal);    
    
    const client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });

    try {
        await client.submitEarnBatch({
            sender:  sender,
            earns: earns,
        });
        fail();
    } catch (error) {
        expect(error).toBeInstanceOf(NoSubsidizerError);
    }

    const result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
        subsidizer: appSubsidizer,
    });
    expect(result.txId).toEqual(txId);
    expect(result.txError).toBeUndefined();
    expect(result.earnErrors).toBeUndefined();
    
    expect(request).toBeDefined();
    const tx = request!.tx;

    expect(tx.signatures).toHaveLength(2);
    expect(tx.signatures[0].publicKey.toBuffer()).toEqual(appSubsidizer.publicKey().buffer);
    expect(appSubsidizer.kp.verify(tx.serializeMessage(), tx.signatures[0].signature!)).toBeTruthy();
    expect(tx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
    expect(sender.kp.verify(tx.serializeMessage(), tx.signatures[1].signature!)).toBeTruthy();

    const memoInstruction = MemoInstruction.decodeMemo(tx.instructions[0]);
    
    const expected = Memo.new(1, TransactionType.Earn, 1, Buffer.alloc(29));
    expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
    
    expect(tx.instructions).toHaveLength(earnCount + 1);

    for (let i = 0; i < earnCount; i++) {
        const tokenInstruction = TokenInstruction.decodeTransfer(tx.instructions[i + 1]);    
            expect(tokenInstruction.source.toBuffer()).toEqual(sender.publicKey().buffer);
            expect(tokenInstruction.dest.toBuffer()).toEqual(earns[i].destination.buffer);
            expect(tokenInstruction.owner.toBuffer()).toEqual(sender.publicKey().buffer);
            expect(tokenInstruction.amount).toEqual(BigInt((i + 1)));
    }
});
Example #22
Source File: feature-toggle.directive.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgFeatureToggleDirective', () => {
  let fixture: ComponentFixture<TestComponent>;
  let directive: LgFeatureToggleDirective;
  const lgFeatureToggleServiceMock = mock(LgFeatureToggleService);

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ TestComponent, LgFeatureToggleDirective ],
      providers: [
        TemplateRef,
        ViewContainerRef,
        {
          provide: LgFeatureToggleService,
          useFactory: () => instance(lgFeatureToggleServiceMock),
        },
        LgFeatureToggleDirective,
      ],
    });

    fixture = TestBed.createComponent(TestComponent);
    directive = TestBed.inject(LgFeatureToggleDirective);
  });

  describe('when the toggle is set to true', () => {
    it('should enable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: true }));
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('when the toggle is set to false', () => {
    it('should disable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: false }));
      fixture.detectChanges();

      const de = fixture.debugElement.query(By.css('#feature'));

      expect(de).toBeNull();
    });
  });

  describe('when the toggle is set to undefined', () => {
    it('should enable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: undefined }));
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('when the defaultHide is set to False and feature is undefined', () => {
    it('should enable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: undefined }));
      directive.setOptions(null);
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('when the defaultHide is set to True and feature is undefined', () => {
    it('should disable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: undefined }));

      directive.setOptions({
        defaultHide: true,
      } as LgFeatureToggleOptions);

      const de = fixture.debugElement.query(By.css('#feature'));

      expect(de).toBeNull();
    });
  });

  describe('when toggles$ returns an empty object', () => {
    it('should enable the elements that have the lgFeatureToggle directive', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({}));
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('cleanup', () => {
    it('should unsubscribe only when there is a subscription in ngOnDestroy', () => {
      const mockSubscription = jasmine.createSpyObj('Subscription', [ 'unsubscribe' ]);

      directive.subscription = mockSubscription;

      directive.ngOnDestroy();

      expect(mockSubscription.unsubscribe).toHaveBeenCalledTimes(1);
    });
  });
});
Example #23
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitEarnBatch failures", async() => {
    const internal = mock(InternalClient);

    // ensure top level bad requests are rejected
    const sender = PrivateKey.random();
    const badBatch: EarnBatch = {
        sender: sender,
        earns: [
            {
                destination: PrivateKey.random().publicKey(),
                quarks: new BigNumber(10),
                invoice: {
                    Items: [
                        {
                            title: "test",
                            amount: new BigNumber(10),
                        }
                    ]
                }
            },
        ],
    };

    let client = new Client(Environment.Test, {
        internal: instance(internal),
    });
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("without an app index");
    }

    badBatch.earns.push({
        destination: PrivateKey.random().publicKey(),
        quarks: new BigNumber(10),
    });

    client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("all or none");
    }

    // too few earns
    const earns = new Array<Earn>();
    badBatch.earns = earns;
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("at least 1");
    }

    // too many earns
    for (let i = 0; i < 16; i++) {
        const dest = PrivateKey.random();
        earns.push({
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
        });
    }
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("more than 15");
    }

    // reduce to max number of earns of 15
    earns.pop();

    let failWith: TransactionErrors | undefined;
    when(internal.signTransaction(anything(), anything()))
        .thenCall((tx: Transaction) => {
            const result = new SignTransactionResult();
            if (tx.feePayer!.toBuffer().equals(subsidizer)){
                tx.partialSign(new Account(subsidizerKey.secretKey()));
            }
            result.TxId = tx.signature ? tx.signature : undefined;
            return Promise.resolve(result);
        });
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall(() => {
            if (!failWith) {
                return Promise.resolve(new SubmitTransactionResult());
            }

            return Promise.resolve({
                TxId: Buffer.alloc(32),
                Errors: failWith,
            });
        });

    setGetServiceConfigResp(internal);
    setGetRecentBlockhashResp(internal);    
    
    client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });

    let result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
    });
    expect(result.txId).toEqual(Buffer.alloc(32));
    expect(result.txError).toBeUndefined();
    expect(result.earnErrors).toBeUndefined();

    failWith = {
        TxError: new InsufficientFee()
    };
    result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
    });
    expect(result.txId).toEqual(Buffer.alloc(32));
    expect(result.txError).toBeInstanceOf(InsufficientFee);
    expect(result.earnErrors).toBeUndefined();

    failWith = {
        TxError: new InsufficientBalance(),
        PaymentErrors: new Array<Error>(15),
    };
    for (let i = 0; i < 15; i++) {
        if (i%2 == 0) {
            failWith.PaymentErrors![i] = new InsufficientBalance();
        }
    }
    result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
    });
    expect(result.txId).toEqual(Buffer.alloc(32));
    expect(result.txError).toBeInstanceOf(InsufficientBalance);
    expect(result.earnErrors).toBeDefined();
    expect(result.earnErrors!).toHaveLength(8);
    for (let i = 0; i < 15; i++) {
        if (i%2 == 0) {
            expect(result.earnErrors![i/2].error).toBeInstanceOf(InsufficientBalance);
            expect(result.earnErrors![i/2].earnIndex).toEqual(i);
        }
    }
});
Example #24
Source File: brand-icon.component.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgBrandIconComponent', () => {
  let component: LgBrandIconComponent;
  let fixture: ComponentFixture<LgBrandIconComponent>;
  let brandIconRegistryMock: LgBrandIconRegistry;

  beforeEach(waitForAsync(() => {
    brandIconRegistryMock = mock(LgBrandIconRegistry);

    TestBed.configureTestingModule({
      declarations: [ LgBrandIconComponent ],
      providers: [
        {
          provide: LgBrandIconRegistry,
          useFactory: () => instance(brandIconRegistryMock),
        },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LgBrandIconComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should add the generic brand-icon class', () => {
    expect(fixture.nativeElement.getAttribute('class')).toContain('lg-brand-icon');
  });

  it('should set `aria-hidden` to true', () => {
    expect(fixture.nativeElement.getAttribute('aria-hidden')).toBe('true');
  });

  describe('setting the name', () => {
    it('should append the correct svg element to the component', () => {
      expect(fixture.nativeElement.querySelector('#test')).toBeNull();
      expect(fixture.nativeElement.querySelector('svg')).toBeNull();

      when(brandIconRegistryMock.getBrandIcon('sun')).thenReturn(
        '<svg id="test">test-svg<path id="lg-icon-fill-primary"></path></svg>',
      );

      component.name = 'sun';
      fixture.detectChanges();

      expect(fixture.nativeElement.querySelector('#test')).toBeNull();

      expect(
        /lg-brand-icon-\d-\d/.test(
          fixture.nativeElement.querySelector('svg').getAttribute('id'),
        ),
      ).toBeTrue();

      const pathEl = fixture.nativeElement.querySelector('path');

      expect(pathEl.getAttribute('id')).not.toContain('lg-icon-fill-primary');
      expect(pathEl.getAttribute('data-colour')).toContain('lg-icon-fill-primary');
    });
  });

  describe('the colour input', () => {
    beforeEach(() => {
      when(brandIconRegistryMock.getBrandIcon('sun')).thenReturn(
        '<svg id="test">test-svg<path id="lg-icon-fill-primary"></path></svg>',
      );

      component.name = 'sun';
    });

    describe('when not specified', () => {
      it('shouldn\'t set the fill colour', () => {
        fixture.detectChanges();
        const el = fixture.nativeElement.querySelector(
          '[data-colour="lg-icon-fill-primary"]',
        );

        expect(el.style.fill).toEqual('');
      });
    });

    describe('when specified', () => {
      it('should apply the specific colour', () => {
        component.colour = '--colour-css-variable';
        fixture.detectChanges();
        const el = fixture.nativeElement.querySelector(
          '[data-colour="lg-icon-fill-primary"]',
        );

        expect(el.style.fill).toEqual('var(--colour-css-variable)');
      });
    });
  });

  it('when the icon isn\'t coloured it should not set the fill style', () => {
    when(brandIconRegistryMock.getBrandIcon('sun')).thenReturn(
      '<svg id="test">test-svg<path id="no-color"></path></svg>',
    );

    component.name = 'sun';

    fixture.detectChanges();
    const el = fixture.nativeElement.querySelector('path[id^="lg-brand-icon-"]');

    expect(el.getAttribute('data-colour')).toBeNull();
    expect(el.style.fill).toEqual('');
  });

  describe('the size input', () => {
    describe('when not specified', () => {
      it('should set the `sm` class modifier', () => {
        expect(fixture.nativeElement.getAttribute('class')).toContain(
          'lg-brand-icon--sm',
        );
      });
    });

    describe('when specified', () => {
      it('should set the correct class modifier', () => {
        component.size = 'md';
        fixture.detectChanges();

        expect(fixture.nativeElement.getAttribute('class')).not.toContain(
          'lg-brand-icon--sm',
        );

        expect(fixture.nativeElement.getAttribute('class')).toContain(
          'lg-brand-icon--md',
        );
      });
    });
  });
});
Example #25
Source File: swagger-provider.spec.ts    From adonis5-swagger with MIT License 4 votes vote down vote up
describe('Swagger provider', () => {
	async function createAdonisApp(mockedServices: Partial<ContainerBindings>) {
		const app = await new AdonisApplication([], []).loadApp()
		for (const [alias, mockedService] of Object.entries(mockedServices)) {
			app.iocContainer.bind(alias, () => mockedService)
		}

		return app
	}

	describe('Swagger enabled', () => {
		let testUrl = 'testUrl'
		let configMock: ConfigContract
		let routerMock: RouterContract
		let routerForMiddlewareMock: RouteContract
		let app: AdonisApplication

		beforeAll(async () => {
			configMock = mock(Config)
			when(configMock.get('swagger.uiEnabled', true)).thenReturn(true)
			when(configMock.get('swagger.specEnabled', true)).thenReturn(true)
			when(configMock.get('swagger.uiUrl', 'docs')).thenReturn('docs')
			when(configMock.get('swagger.specUrl')).thenReturn(testUrl)
			when(configMock.get('swagger.middleware', [])).thenReturn([])
			when(configMock.get('swagger.options', {})).thenReturn({})

			routerMock = mock(Router)
			routerForMiddlewareMock = mock(Route)
			const routeForMiddlewareInstance = instance(routerForMiddlewareMock)
			when(routerMock.get(`docs/:fileName?`, anything())).thenReturn(routeForMiddlewareInstance)
			when(routerMock.get(testUrl, anything())).thenReturn(routeForMiddlewareInstance)

			app = await createAdonisApp({
				'Adonis/Core/Config': instance(configMock),
				'Adonis/Core/Route': instance(routerMock),
			})
		})

		it('should instantiate provider with enabled swagger', async () => {
			const swaggerProvider = new SwaggerProvider(app.application)
			await swaggerProvider.register()
			await swaggerProvider.boot()

			verify(configMock.get('swagger.uiEnabled', true)).once()
			verify(configMock.get('swagger.specEnabled', true)).once()
			verify(configMock.get('swagger.uiUrl', 'docs')).once()
			verify(configMock.get('swagger.specUrl')).once()

			verify(routerMock.get(testUrl, anything())).once()
			verify(routerForMiddlewareMock.middleware(anything())).twice()
		})

		afterAll(async () => {
			await app.stopApp()
		})
	})

	describe('Swagger disabled', () => {
		let testUrl = 'testUrl'
		let configMock: ConfigContract
		let routerMock: RouterContract
		let adonisApp: AdonisApplication

		beforeAll(async () => {
			configMock = mock(Config)
			when(configMock.get('swagger.uiEnabled')).thenReturn(false)
			when(configMock.get('swagger.specEnabled')).thenReturn(false)

			routerMock = mock(Router)
			when(routerMock.get(testUrl, anything())).thenReturn({} as any)

			adonisApp = await createAdonisApp({
				'Adonis/Core/Config': instance(configMock),
				'Adonis/Core/Route': instance(routerMock),
			})
		})

		it('should not init swagger module, swagger was disabled', async () => {
			const swaggerProvider = new SwaggerProvider(adonisApp.application)
			await swaggerProvider.register()
			await swaggerProvider.boot()

			verify(configMock.get('swagger.specEnabled')).never()
			verify(configMock.get('swagger.uiEnabled')).never()
			verify(configMock.get('swagger.uiUrl', 'docs')).never()
			verify(configMock.get('swagger.specUrl')).never()

			verify(routerMock.get(testUrl, anything())).never()
		})

		afterAll(async () => {
			await adonisApp.stopApp()
		})
	})
})
Example #26
Source File: userStorage.spec.ts    From space-sdk with MIT License 4 votes vote down vote up
initStubbedStorage = (): { storage: UserStorage; mockBuckets: Buckets } => {
  const mockBuckets: Buckets = mock();
  when(mockBuckets.getOrCreate(anyString(), anything())).thenReturn(
    Promise.resolve({
      root: {
        ...mock<Root>(),
        key: 'myBucketKey',
      },
    }),
  );

  // const mockMetadataStore: UserMetadataStore = mock();
  // when(mockMetadataStore.findBucket(anyString())).thenReturn(Promise.resolve(undefined));
  // when(mockMetadataStore.createBucket(anyString(), anyString())).thenReturn(Promise.resolve({
  //   slug: 'myBucketKey',
  //   encryptionKey: new Uint8Array(80),
  //   dbId: 'dbId',
  // }));

  const storage = new UserStorage(
    {
      identity: mockIdentity,
      token: '',
      endpoint: 'http://space-auth-endpoint.com',
      storageAuth: {
        key: 'random-key',
        token: 'token',
        sig: 'sig',
        msg: 'msg',
      },
    },
    {
      bucketsInit: () => instance(mockBuckets),
      metadataStoreInit: async (): Promise<UserMetadataStore> =>
        // commenting this out now because it causes test to silently fail
        // return instance(mockMetadataStore); // to be fixed later
        // eslint-disable-next-line implicit-arrow-linebreak
        Promise.resolve({
          createBucket(bucketSlug: string, dbId: string): Promise<BucketMetadata> {
            return Promise.resolve({
              bucketKey: 'testkey',
              slug: 'myBucketKey',
              encryptionKey: new Uint8Array(80),
              dbId: 'dbId',
            });
          },
          findBucket(bucketSlug: string): Promise<BucketMetadata | undefined> {
            return Promise.resolve({
              bucketKey: 'testkey',
              slug: 'myBucketKey',
              encryptionKey: new Uint8Array(80),
              dbId: 'dbId',
            });
          },
          listBuckets(): Promise<BucketMetadata[]> {
            return Promise.resolve([]);
          },
          upsertFileMetadata(input: FileMetadata): Promise<FileMetadata> {
            return Promise.resolve({ ...input, bucketSlug: 'myBucket', dbId: '', path: '/' });
          },
          findFileMetadata(bucketSlug, dbId, path): Promise<FileMetadata | undefined> {
            return Promise.resolve({
              uuid: 'generated-uuid',
              mimeType: 'generic/type',
              encryptionKey,
              bucketSlug,
              dbId,
              path,
            });
          },
          findFileMetadataByUuid(): Promise<FileMetadata | undefined> {
            return Promise.resolve({
              mimeType: 'generic/type',
              bucketSlug: 'myBucket',
              bucketKey: 'myBucketKey',
              dbId: 'mockThreadId',
              path: '/',
              encryptionKey,
            });
          },
          setFilePublic(_metadata: FileMetadata): Promise<void> {
            return Promise.resolve();
          },
          async upsertSharedWithMeFile(data: SharedFileMetadata): Promise<SharedFileMetadata> {
            return data;
          },
          async listSharedWithMeFiles(): Promise<SharedFileMetadata[]> {
            return [];
          },
          async upsertSharedByMeFile(data: SharedFileMetadata): Promise<SharedFileMetadata> {
            return data;
          },
          async findSharedFilesByInvitation(id: string): Promise<SharedFileMetadata | undefined> {
            return undefined;
          },
          async listSharedByMeFiles(): Promise<SharedFileMetadata[]> {
            return [];
          },
          async addUserRecentlySharedWith(data: ShareUserMetadata): Promise<ShareUserMetadata> {
            return data;
          },
          async listUsersRecentlySharedWith(): Promise<ShareUserMetadata[]> {
            return [];
          },
          async getNotificationsLastSeenAt():Promise<number> {
            return Date.now();
          },
          async setNotificationsLastSeenAt(timestamp:number):Promise<void> {
            noop;
          },
        }),
    },
  );

  return { storage, mockBuckets };
}
Example #27
Source File: c-form-select.test.ts    From bindable with MIT License 4 votes vote down vote up
describe('c-form-select component', () => {
    let component: any;
    let cFormSelect: any;
    let mockFn: any;
    const searchOptions = [
        {
            text: 'Value 1',
            value: 'value1',
        },
        {
            text: 'Value 2',
            value: 'Value2',
        },
    ];
    const searchSimpleOptions = ['Value 1', 'Value 2', 'Value 3'];

    beforeAll(() => {
        // mock select2
        const select2Response = {
            on: jest.fn().mockImplementation(() => select2Response),
        };
        const mockSelect2 = jest.fn().mockImplementation(options => select2Response);
        // @ts-ignore
        $.fn.select2 = mockSelect2;

        // Mock throttle
        // @ts-ignore
        jest.spyOn(_, 'throttle').mockImplementation(func => func);
    });

    beforeEach(() => {
        mockFn = jest.fn();
    });

    describe('Integration', () => {
        afterEach(() => {
            component.dispose();
        });

        it('testing multiple', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select multiple.bind="customMultiple"></c-form-select>')
                .boundTo({
                    customMultiple: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.multiple).toBe(false);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test if search is enabled
        it('testing search', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select search.bind="customsearch"></c-form-select>')
                .boundTo({
                    customSearch: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.search).toBe(false);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test if simple is enabled
        it('testing simple', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select simple.bind="customSimple"></c-form-select>')
                .boundTo({
                    customSimple: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.simple).toBe(false);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test if virtual is enabled
        it('testing virtual', async done => {
            // @ts-ignore
            global.innerHeight = 100;
            component = StageComponent.withResources()
                .inView('<c-form-select virtual.bind="customVirtual"></c-form-select>')
                .boundTo({
                    customVirtual: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.virtual).toBe(false);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test if isLoading is enabled
        it('testing isLoading', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select is-loading.bind="customIsLoading"></c-form-select>')
                .boundTo({
                    customIsLoading: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.isLoading).toBe(false);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test if isLoadingMore is enabled
        it('testing isLoadingMore', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select is-loading-more.bind="customIsLoadingMore"></c-form-select>')
                .boundTo({
                    customIsLoadingMore: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.isLoadingMore).toBe(false);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test if reorder is enabled
        it('testing reorder', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select reorder.bind="customReorder"></c-form-select>')
                .boundTo({
                    customReorder: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.reorder).toBe(false);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        it('should set default placeholder text', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select placeholder.bind="customPlaceholder"></c-form-select>')
                .boundTo({
                    customPlaceholder: 1,
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.placeholder).toBe('Select an Option');
                component = StageComponent.withResources()
                    .inView('<c-form-select placeholder.bind="customPlaceholder" multiple.bind="true"></c-form-select>')
                    .boundTo({
                        customPlaceholder: 1,
                    });
                await bootStrapEnvironment(component);
                expect(component.viewModel.placeholder).toBe('Select Multiple Options');
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        it('should set placeholder text', async done => {
            component = StageComponent.withResources()
                .inView('<c-form-select placeholder.bind="customPlaceholder"></c-form-select>')
                .boundTo({
                    customPlaceholder: 'placeholder test',
                });

            try {
                await bootStrapEnvironment(component);
                expect(component.viewModel.placeholder).toBe('placeholder test');
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test search button with no action
        it('tests when searching when no action handler defined', async done => {
            const queryStr = 'c-button';
            component = StageComponent.withResources()
                .inView('<c-form-select options.bind="searchOptions" search.bind="true"></c-form-select>')
                .boundTo({
                    searchOptions,
                });

            try {
                await bootStrapEnvironment(component);
                const spyOn = jest.spyOn(component.viewModel, 'searchSelect');
                (document.querySelector(queryStr) as any).click();
                expect(spyOn).toHaveBeenCalled();
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test simple search button with action handler
        it('tests simple searching with action handler', async done => {
            const template = `
            <c-form-select
                simple.bind="true"
                options.bind="searchSimpleOptions"
                search.bind="true"
                actions.bind="callbacks">
            </c-form-select>
        `;
            const queryStr = 'c-button';
            component = StageComponent.withResources()
                .inView(template)
                .boundTo({
                    searchSimpleOptions,
                    callbacks: {
                        onSearch: mockFn,
                    },
                });

            try {
                await bootStrapEnvironment(component);
                const spyOn = jest.spyOn(component.viewModel, 'searchSelect');
                (document.querySelector(queryStr) as any).click();
                component.viewModel.filterSearch('val');
                expect(spyOn).toHaveBeenCalled();
                expect(mockFn).toHaveBeenCalled();
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        it('should highlight all with cmd+a or ctrl+a on a virtual select', async done => {
            const template = `
            <c-form-select
                options.bind="searchOptions"
                virtual.bind="true"
            >
            </c-form-select>
        `;
            component = StageComponent.withResources()
                .inView(template)
                .boundTo({
                    searchOptions,
                });

            try {
                await bootStrapEnvironment(component);
                document.getElementById(component.viewModel.id).focus();
                document.dispatchEvent(
                    new window.KeyboardEvent('keydown', {
                        key: 'a',
                        metaKey: true,
                    }),
                );
                const expected = [
                    {value: 'value1', text: 'Value 1', selected: true},
                    {value: 'Value2', text: 'Value 2', selected: true},
                ];
                expect(component.viewModel.virtualOptions).toEqual(expected);

                await bootStrapEnvironment(component);
                expect(component.viewModel.virtualOptions[0].selected).toBeFalsy();
                document.getElementById(component.viewModel.id).focus();
                document.dispatchEvent(
                    new window.KeyboardEvent('keydown', {
                        ctrlKey: true,
                        key: 'a',
                    }),
                );
                expect(component.viewModel.virtualOptions).toEqual(expected);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

        // Test select value changed and executes on change event.
        it('calls selectValueChanged with action handler', async done => {
            const template = `
            <c-form-select
                simple.bind="true"
                options.bind="searchSimpleOptions"
                search.bind="true"
                value.bind="selectValue"
                actions.bind="callbacks">
            </c-form-select>
        `;
            component = StageComponent.withResources()
                .inView(template)
                .boundTo({
                    searchSimpleOptions,
                    callbacks: {
                        onChange: mockFn,
                    },
                });

            try {
                await bootStrapEnvironment(component);
                component.viewModel.selectValueChanged('Value 2', 'Value 1');
                expect(mockFn).toHaveBeenCalled();

                component.viewModel.selectValue = 'Value 2';
                component.viewModel.selectValueChanged('Value 2', 'Value 1');
                expect(component.viewModel.disableDisplay).toEqual('Value 2');

                component.viewModel.simple = false;
                component.viewModel.options = searchOptions;
                component.viewModel.enableSelect2 = true;
                component.viewModel.selectValue = 'Value2';
                component.viewModel.selectValueChanged('value2', 'value1');
                expect(component.viewModel.disableDisplay).toEqual('Value 2');

                done();
            } catch (e) {
                done.fail(e);
            }
        });

        describe('#moveItems', () => {
            describe('simple list', () => {
                test('when dir is 1', async done => {
                    const template = `
                    <c-form-select
                        simple.bind="true"
                        options.bind="searchSimpleOptions"
                        search.bind="true"
                        actions.bind="callbacks"
                        select-value.bind="selectedValues"
                    >
                    </c-form-select>
                `;
                    component = StageComponent.withResources()
                        .inView(template)
                        .boundTo({
                            searchSimpleOptions,
                            callbacks: {
                                onChange: mockFn,
                            },
                            selectedValues: ['Value 2'],
                        });

                    try {
                        await bootStrapEnvironment(component);
                        component.viewModel.moveItems(1);
                        expect(multiIndexSplicer).toHaveBeenCalled();
                        done();
                    } catch (e) {
                        done.fail(e);
                    }
                });

                test('when dir is -1', async done => {
                    const template = `
                    <c-form-select
                        simple.bind="true"
                        options.bind="searchSimpleOptions"
                        search.bind="true"
                        actions.bind="callbacks"
                        select-value.bind="selectedValues"
                    >
                    </c-form-select>
                `;
                    component = StageComponent.withResources()
                        .inView(template)
                        .boundTo({
                            searchSimpleOptions,
                            callbacks: {
                                onChange: mockFn,
                            },
                            selectedValues: ['Value 2'],
                        });

                    try {
                        await bootStrapEnvironment(component);
                        component.viewModel.moveItems(-1);
                        expect(multiIndexSplicer).toHaveBeenCalled();
                        done();
                    } catch (e) {
                        done.fail(e);
                    }
                });
            });

            describe('non-simple list', () => {
                test('when dir is 1', async done => {
                    const template = `
                    <c-form-select
                        options.bind="searchOptions"
                        search.bind="true"
                        actions.bind="callbacks"
                        select-value.bind="selectedValues"
                    >
                    </c-form-select>
                `;
                    component = StageComponent.withResources()
                        .inView(template)
                        .boundTo({
                            searchOptions,
                            callbacks: {
                                onChange: mockFn,
                            },
                            selectedValues: ['Value 2'],
                        });

                    try {
                        await bootStrapEnvironment(component);
                        component.viewModel.moveItems(1);
                        expect(multiIndexSplicer).toHaveBeenCalled();
                        done();
                    } catch (e) {
                        done.fail(e);
                    }
                });

                test('when dir is -1', async done => {
                    const template = `
                    <c-form-select
                        options.bind="searchOptions"
                        search.bind="true"
                        actions.bind="callbacks"
                        select-value.bind="selectedValues"
                    >
                    </c-form-select>
                `;
                    component = StageComponent.withResources()
                        .inView(template)
                        .boundTo({
                            searchOptions,
                            callbacks: {
                                onChange: mockFn,
                            },
                            selectedValues: ['Value 2'],
                        });

                    try {
                        await bootStrapEnvironment(component);
                        component.viewModel.moveItems(-1);
                        expect(multiIndexSplicer).toHaveBeenCalled();
                        done();
                    } catch (e) {
                        done.fail(e);
                    }
                });
            });
        });

        describe('c-form-select component scrolling', () => {
            let viewModel;
            const template = `
                <c-form-select
                    simple.bind="true"
                    options.bind="searchSimpleOptions"
                    search.bind="true"
                    actions.bind="callbacks">
                </c-form-select>
            `;

            beforeEach(async done => {
                mockFn = jest.fn();
                component = StageComponent.withResources()
                    .inView(template)
                    .boundTo({
                        searchSimpleOptions,
                        callbacks: {
                            onSearch: mockFn,
                        },
                    });
                await bootStrapEnvironment(component);
                viewModel = component.viewModel;
                done();
            });

            it('Call onScrollBottom if checkLoadMore is true and onScrollBottom is not defined', () => {
                const spy = jest.spyOn(viewModel, 'onScroll');
                viewModel.onScroll();
                viewModel.scrollToLoad = {
                    onSearch: mockFn,
                };
                viewModel.onScroll();
                expect(spy).toHaveBeenCalled();
            });

            it('Call onScrollBottom and onScrollBottom', () => {
                const spy = jest.spyOn(viewModel, 'onScroll');
                const mockOnScrollBottom = jest.fn();
                // viewModel.onScroll();
                viewModel.scrollToLoad = {
                    onSearch: mockFn,
                };
                viewModel.actions.onScrollBottom = mockOnScrollBottom;
                viewModel.onScroll();
                expect(spy).toHaveBeenCalled();
                expect(mockOnScrollBottom).toHaveBeenCalled();
            });
        });

        describe('CSS Classes', () => {
            it('css class: select', async done => {
                component = StageComponent.withResources().inView('<c-form-select></c-form-select>');

                try {
                    await bootStrapEnvironment(component);
                    expect(component.viewModel.styles.select).not.toBe(undefined);
                    done();
                } catch (e) {
                    done.fail(e);
                }
            });

            it('css class: error', async done => {
                component = StageComponent.withResources().inView('<c-form-select></c-form-select>');

                try {
                    await bootStrapEnvironment(component);
                    expect(component.viewModel.styles.error).not.toBe(undefined);
                    done();
                } catch (e) {
                    done.fail(e);
                }
            });

            it('css class: label-wrapper', async done => {
                component = StageComponent.withResources().inView('<c-form-select></c-form-select>');

                try {
                    await bootStrapEnvironment(component);
                    expect(component.viewModel.styles['label-wrapper']).not.toBe(undefined);
                    done();
                } catch (e) {
                    done.fail(e);
                }
            });

            it('css class: multiple', async done => {
                component = StageComponent.withResources().inView('<c-form-select></c-form-select>');

                try {
                    await bootStrapEnvironment(component);
                    expect(component.viewModel.styles.multiple).not.toBe(undefined);
                    done();
                } catch (e) {
                    done.fail(e);
                }
            });

            it('css class loader', async done => {
                component = StageComponent.withResources().inView('<c-form-select></c-form-select>');

                try {
                    await bootStrapEnvironment(component);
                    expect(component.viewModel.styles.loader).not.toBe(undefined);
                    done();
                } catch (e) {
                    done.fail(e);
                }
            });
        });
    });

    describe('Non UI', () => {
        beforeEach(() => {
            const element = mock(instance(Element));
            cFormSelect = new CFormSelect(element);
        });

        describe('.setupVirtualSelect', () => {
            beforeEach(() => {
                cFormSelect.isLoading = false;
                cFormSelect.virtual = true;
            });
            it('should clear virtualOptions', () => {
                cFormSelect.virtualOptions = [1, 2, 3];
                cFormSelect.setupVirtualSelect();
                expect(cFormSelect.virtualOptions).toEqual([]);
            });
            it('should set virtual options for list of objects', () => {
                cFormSelect.options = searchOptions;
                cFormSelect.setupVirtualSelect();
                const expected = [
                    {value: 'value1', text: 'Value 1', selected: false},
                    {value: 'Value2', text: 'Value 2', selected: false},
                ];
                expect(cFormSelect.virtualOptions).toEqual(expected);
            });
            it('should set virtual options for simple list', () => {
                cFormSelect.options = searchSimpleOptions;
                cFormSelect.setupVirtualSelect();
                const expected = [
                    {value: 'Value 1', text: 'Value 1', selected: false},
                    {value: 'Value 2', text: 'Value 2', selected: false},
                    {value: 'Value 3', text: 'Value 3', selected: false},
                ];
                expect(cFormSelect.virtualOptions).toEqual(expected);
            });
            it('should set the selected value', () => {
                cFormSelect.options = searchOptions;
                cFormSelect.selectValue = 'value1';
                cFormSelect.setupVirtualSelect();
                const expected = [
                    {value: 'value1', text: 'Value 1', selected: true},
                    {value: 'Value2', text: 'Value 2', selected: false},
                ];
                expect(cFormSelect.virtualOptions).toEqual(expected);
            });
            it('should select none', () => {
                cFormSelect.options = searchOptions;
                cFormSelect.selectValue = 'value1';
                cFormSelect.setupVirtualSelect();
                cFormSelect.selectNone();
                expect(cFormSelect.virtualOptions[0].selected).toBeFalsy();
            });
            it('should select virtual option', () => {
                cFormSelect.options = searchOptions;
                cFormSelect.selectValue = 'value1';
                cFormSelect.setupVirtualSelect();
                cFormSelect.selectVirtualOption(jest.fn(), cFormSelect.virtualOptions[0], 0);
                expect(cFormSelect.virtualOptions[0].selected).toBeFalsy();
            });
        });

        describe('.selectVirtualOption', () => {
            beforeEach(() => {
                cFormSelect.isLoading = false;
                cFormSelect.virtual = true;
                cFormSelect.options = searchSimpleOptions;
                cFormSelect.selectValue = 'Value 1';
                cFormSelect.setupVirtualSelect();
            });
            it("should change the selected option's value", () => {
                cFormSelect.selectVirtualOption(jest.fn(), cFormSelect.virtualOptions[0], 0);
                expect(cFormSelect.virtualOptions[0].selected).toBeFalsy();
            });
            it('should not change the value if the component is disabled', () => {
                cFormSelect.state = 'disabled';
                cFormSelect.selectVirtualOption(jest.fn(), cFormSelect.virtualOptions[0], 0);
                expect(cFormSelect.virtualOptions[0].selected).toBeTruthy();
            });
            it('should select multiple if shift key is held', () => {
                cFormSelect.multiple = true;
                cFormSelect.selectVirtualOption(jest.fn(), cFormSelect.virtualOptions[0], 0);
                expect(cFormSelect.lastClicked).toEqual(0);
                cFormSelect.selectVirtualOption({shiftKey: true}, cFormSelect.virtualOptions[2], 2);
                expect(cFormSelect.virtualOptions[1].selected).toBeTruthy();
                cFormSelect.virtualOptions.forEach(o => {
                    o.selected = false;
                });
                cFormSelect.selectVirtualOption({shiftKey: false}, cFormSelect.virtualOptions[2], 2);
                cFormSelect.selectVirtualOption({shiftKey: true}, cFormSelect.virtualOptions[0], 0);
                expect(cFormSelect.virtualOptions[1].selected).toBeTruthy();
            });
        });
    });
});
Example #28
Source File: toggle.component.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgToggleComponent', () => {
  let fixture: ComponentFixture<TestToggleComponent>;
  let component: TestToggleComponent;
  let toggleDebugElement: DebugElement;
  let toggleInstance: LgToggleComponent;
  let inputDebugElement: DebugElement;
  let inputLabelElement: DebugElement;

  const errorStateMatcherMock = mock(LgErrorStateMatcher);

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [ FormsModule, ReactiveFormsModule ],
        declarations: [
          TestToggleComponent,
          LgToggleComponent,
          MockComponents(LgValidationComponent, LgIconComponent),
        ],
        providers: [
          {
            provide: LgErrorStateMatcher,
            useFactory: () => instance(errorStateMatcherMock),
          },
        ],
      }).compileComponents();

      fixture = TestBed.createComponent(TestToggleComponent);
      fixture.detectChanges();
      component = fixture.componentInstance;

      toggleDebugElement = fixture.debugElement.query(By.directive(LgToggleComponent));

      toggleInstance =
        toggleDebugElement.injector.get<LgToggleComponent>(LgToggleComponent);

      inputDebugElement = fixture.debugElement.query(By.css('.lg-toggle__input'));
      inputLabelElement = fixture.debugElement.query(By.css('.lg-toggle__label'));
      fixture.detectChanges();
    }),
  );

  it('sets a unique name for the toggle button', () => {
    expect(
      /lg-toggle-\d/.test(inputDebugElement.nativeElement.getAttribute('name')),
    ).toBe(true);
  });

  it('sets a unique id for the toggle button', () => {
    expect(/lg-toggle-\d/.test(inputDebugElement.nativeElement.getAttribute('id'))).toBe(
      true,
    );
  });

  it('sets the correct modifier class based on the variant', () => {
    component.variant = 'checkbox';

    expect(
      inputLabelElement.nativeElement.classList.contains('lg-toggle__label--switch'),
    ).toBe(false);

    component.variant = 'switch';
    fixture.detectChanges();

    expect(
      inputLabelElement.nativeElement.classList.contains('lg-toggle__label--switch'),
    ).toBe(true);
  });

  it('adds the checkbox icon based on the variant', () => {
    component.variant = 'switch';

    expect(fixture.debugElement.query(By.css('.lg-toggle__checkbox'))).toBeNull();

    component.variant = 'checkbox';
    fixture.detectChanges();

    expect(
      fixture.debugElement.query(By.css('.lg-toggle__checkbox')).nativeElement,
    ).toBeDefined();
  });

  it('links the label to the input field with the correct attributes', () => {
    const id = inputDebugElement.nativeElement.getAttribute('id');

    expect(id).toBeTruthy();
    expect(inputLabelElement.nativeElement.getAttribute('for')).toBe(id);
  });

  it('checks the toggle by default if the value is true', () => {
    expect(inputDebugElement.nativeElement.checked).toBe(false);
    component.umbrella.setValue(true);
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.checked).toBe(true);
  });

  it('updates the model value when a toggle is checked', () => {
    expect(component.umbrella.value).toBe(null);
    fixture.detectChanges();
    inputDebugElement.triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(component.umbrella.value).toBe(true);
  });

  it('triggers the onChange action when the toggle is checked', () => {
    const onChangeSpy = spyOn(toggleInstance, 'onChange');

    inputDebugElement.triggerEventHandler('click', null);

    expect(onChangeSpy).toHaveBeenCalled();
  });

  it('triggers the onBlur action when the toggle is blurred', () => {
    const onBlurSpy = spyOn(toggleInstance, 'onBlur');

    inputDebugElement.triggerEventHandler('blur', null);

    expect(onBlurSpy).toHaveBeenCalledTimes(1);
  });

  it('disables the input field when the property is set', () => {
    expect(inputDebugElement.nativeElement.disabled).toBe(false);
    component.umbrella.disable();
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.disabled).toBe(true);
  });

  it('links the error to the input field with the correct attributes', () => {
    const id = inputDebugElement.nativeElement.getAttribute('id');

    expect(id).toBeTruthy();
    expect(inputLabelElement.nativeElement.getAttribute('for')).toBe(id);
  });

  it('links the error to the fieldset with the correct aria attributes', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.getAttribute('aria-describedBy')).toContain(
      validationTestId,
    );
  });

  it('unlinks the error from the fieldset with the correct aria attributes when valid', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(
      false,
    );

    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.hasAttribute('aria-describedBy')).toBe(false);
    expect(inputDebugElement.nativeElement.getAttribute('aria-invalid')).toBe('false');
  });

  it('adds the error class and the aria-invalid attribute if the form field is invalid', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();

    expect(toggleDebugElement.nativeElement.className).toContain('lg-toggle--error');
    expect(inputDebugElement.nativeElement.getAttribute('aria-invalid')).toBe('true');
  });
});
Example #29
Source File: ModelManager.test.ts    From aem-spa-page-model-manager with Apache License 2.0 4 votes vote down vote up
describe('ModelManager ->', () => {
    const PAGE_MODEL_LOAD_EVENT_OPTIONS = {
        detail: {
            model: PAGE_MODEL
        }
    };

    function expectPageModelLoadedEventFired() {
        expect(PathUtils.dispatchGlobalCustomEvent).toHaveBeenCalled();
        expect(PathUtils.dispatchGlobalCustomEvent).toHaveBeenCalledWith(EventType.PAGE_MODEL_LOADED, PAGE_MODEL_LOAD_EVENT_OPTIONS);
    }

    function assertAsyncModelFetched() {
        expectPageModelLoadedEventFired();

        return ModelManager.getData().then((data) => {
            assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
        });
    }

    function mockTheFetch(path: any, data: any) {
        REQUEST_MAP[path] = data;
    }

    let pathName = '';
    let metaProps: { [key: string]: string } = {};
    const isRouteExcludedSpy = isRouteExcluded as jest.MockedFunction<(route: string) => boolean>;

    beforeEach(() => {
        metaProps = {};
        metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;
        pathName = PAGE_PATH;

        when(ModelClientMock.fetch(anyString())).thenReturn(Promise.resolve(PAGE_MODEL));
        when(ModelClientMock.fetch(PAGE_MODEL_URL)).thenReturn(Promise.resolve(PAGE_MODEL));
        when(ModelClientMock.fetch(CHILD_MODEL_URL)).thenReturn(Promise.resolve(content_test_page_root_child0000_child0010));
        when(ModelClientMock.fetch(NON_EXISTING_MODEL_URL))
            .thenReturn(Promise.reject({ response: { status: 404, statusText: 'Could not find page' } }));
        when(ModelClientMock.fetch(ERROR_MODEL_URL)).thenReturn(Promise.reject('Some Error without json'));

        when(ModelClientMock.fetch(ERROR_MODEL_URL_404)).thenReturn(Promise.resolve(ERROR_PAGE_MODEL_404));
        when(ModelClientMock.fetch(ERROR_MODEL_URL_500)).thenReturn(Promise.resolve(ERROR_PAGE_MODEL_500));

        modelClient = instance(ModelClientMock);
        jest.spyOn(PathUtils, 'getMetaPropertyValue').mockImplementation((val) => metaProps[val]);
        jest.spyOn(PathUtils, 'dispatchGlobalCustomEvent');
        jest.spyOn(PathUtils, 'getCurrentPathname').mockImplementation(() => pathName);
        isRouteExcludedSpy.mockImplementation(() => false);
        mockTheFetch(PAGE_MODEL_URL, PAGE_MODEL);
    });

    afterEach(() => {
        reset(ModelClientMock);
        pathName = '';
    });

    describe('initialize ->', () => {
        describe('Initialization without config object ->', () => {
            it('should NOT fetch remote data on initialization when the model is provided', () => {
                return ModelManager.initialize({ model: PAGE_MODEL }).then((data) => {
                    expectPageModelLoadedEventFired();
                    expect(data).toEqual(PAGE_MODEL);
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch remote data on initialization - root path as meta property', () => {
                metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;

                return ModelManager.initialize().then((data) => {
                    expectPageModelLoadedEventFired();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch remote data on initialization - root path as currentPathname', () => {
                pathName = PAGE_MODEL_URL;

                return ModelManager.initialize().then((data) => {
                    expectPageModelLoadedEventFired();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch remote data on initialization - root path as a parameter', () => {
                return ModelManager.initialize(PAGE_PATH).then((data) => {
                    expectPageModelLoadedEventFired();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
        });

        it('should fetch remote data on initialization', () => {
            return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
                verify(modelClient.fetch(anyString()));
                assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
            });
        });

        it('should fail when initialized on non-browser with invlid config', () => {
            pathName = '';

            // disable console.error within the test
            jest.spyOn(console, 'error').mockImplementation();

            //simulate non browser for the test
            const windowSpy = jest.spyOn(global, 'window', 'get');

            windowSpy.mockImplementation();

            try {
                ModelManager.initialize();
            } catch (err) {
                assert.strictEqual(err.name, 'Error');
            }
            windowSpy.mockRestore();
        });

        it('should throw error when initialized without model url', () => {
            metaProps = {};
            pathName = '';
            try {
                ModelManager.initialize();
            } catch (err) {
                assert.strictEqual(err.name, 'Error');
            }
        });

        it('should throw error when initialized with invalid model url', () => {
            try {
                ModelManager.initialize({ path: '?abc' });
            } catch (err) {
                assert.strictEqual(err.name, 'Error');
            }
        });

        it('should not make concurrent server calls on duplicate request', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();
                pathName = '/content/test/duplicate/request';

                when(ModelClientMock.fetch(pathName)).thenReturn(new Promise((resolve) => {
                    setTimeout(() => resolve(PAGE_MODEL), 200);
                }));

                const promises: any[] = [];

                promises.push(ModelManager._fetchData(pathName));
                promises.push(ModelManager._fetchData(pathName));
                promises.push(ModelManager._fetchData(pathName));

                return Promise.all(promises).then(() => {
                    for (let i = 0; i < promises.length - 1; ++i) {
                        expect(promises[i]).toEqual(promises[i + 1]);
                    }
                });
            });
        });

        describe('when the request is for an asynchronous subpage -- ', () => {
            beforeEach(() => {
                pathName = '/content/test/pageNotInModel';
                metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = '/content/test';
            });

            it('should fetch data twice on initialization', () => {
                return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
                    expectPageModelLoadedEventFired();
                    verify(ModelClientMock.fetch(anyString())).times(2);
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch data once on initialization when sub page route path is excluded', () => {
                isRouteExcludedSpy.mockReturnValue(true);
                return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
                    expectPageModelLoadedEventFired();
                    verify(ModelClientMock.fetch(anyString())).times(1);
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
         });

        it('should not fetch data on initialization', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then((data) => {
                expectPageModelLoadedEventFired();
                // verify(ModelClientMock.fetch(anyString())).never();
                assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
            });
        });

        it('should not fetch data', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();

                return ModelManager.getData(CHILD_PATH).then((data) => {
                    verify(ModelClientMock.fetch(CHILD_MODEL_URL)).never();
                    assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
                });
            });
        });

        it('should fetch all the data', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();

                return ModelManager.getData().then((data) => {
                    verify(ModelClientMock.fetch(CHILD_MODEL_URL)).never();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
        });

        it('should fetch data if forced', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();

                return ModelManager.getData({ path: CHILD_PATH, forceReload: true }).then((data) => {
                    verify(ModelClientMock.fetch(anyString())).times(1);
                    assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
                });
            });
        });
    });

    describe('initializeAsync ->', () => {
        describe('Initialization without config object ->', () => {
            it('should fetch remote data on initialization - root path as meta property', () => {
                metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;
                ModelManager.initializeAsync();
                assertAsyncModelFetched();
            });

            it('should fetch remote data on initialization - root path as currentPathname', () => {
                pathName = PAGE_MODEL_URL;
                ModelManager.initializeAsync();
                assertAsyncModelFetched();
            });

            it('should initialize model store when no root path is provided', () => {
                metaProps = {};
                pathName = '';
                ModelManager.initializeAsync();

                return ModelManager.getData({ path: PAGE_MODEL_URL }).then((data) => {
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
        });

        it('should fetch standalone item data', () => {
            metaProps = {};
            pathName = '';
            ModelManager.initializeAsync();

            return ModelManager.getData({ path: CHILD_PATH }).then((data) => {
                assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
            });
        });
        it('should throw error when fetching data without initialization', () => {
            ModelManager.getData({ path: PAGE_MODEL_URL }).then((data) => {
                assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
            });
        });

        it('should NOT fetch remote data on initialization when the model is provided', () => {
            ModelManager.initializeAsync({ model: PAGE_MODEL });
            assertAsyncModelFetched();
        });

        it('should fetch remote data on initialization - root path as a parameter', () => {
            ModelManager.initializeAsync(PAGE_PATH);
            assertAsyncModelFetched();
        });

        it('should fetch remote data on initialization', () => {
            ModelManager.initializeAsync({ path: PAGE_PATH, modelClient: modelClient });
            verify(modelClient.fetch(anyString()));
            assertAsyncModelFetched();
        });

        it('should load a 404 error page.', async () => {

            const configuration:ModelManagerConfiguration = {
                path: PAGE_PATH,
                modelClient: modelClient,
                errorPageRoot: ERROR_PAGE_ROOT
            };
            const data:Model = await ModelManager.initialize(configuration);
            verify(modelClient.fetch(anyString()));
            assert.deepEqual(data, PAGE_MODEL, 'data should be correct');

            const nonExistingData = await ModelManager._fetchData(NON_EXISTING_PATH);
            assert.deepEqual(nonExistingData, ERROR_PAGE_MODEL_404, 'data should be correct');

        });

        it('should load a 500 error page.', async () => {

            const configuration:ModelManagerConfiguration = {
                path: PAGE_PATH,
                modelClient: modelClient,
                errorPageRoot: ERROR_PAGE_ROOT
            };
            const data:Model = await ModelManager.initialize(configuration);
            verify(modelClient.fetch(anyString()));
            assert.deepEqual(data, PAGE_MODEL, 'data should be correct');

            const nonExistingData = await ModelManager._fetchData(PAGE_WITH_ERROR_PATH);
            assert.deepEqual(nonExistingData, ERROR_PAGE_MODEL_500, 'data should be correct');

        });
    });
});