ts-mockito#anything TypeScript Examples

The following examples show how to use ts-mockito#anything. 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 setGetServiceConfigResp(txClientV4: transactiongrpcv4.TransactionClient) {
    when(txClientV4.getServiceConfig(anything(), anything(), anything()))
        .thenCall((_, md: grpc.Metadata, callback) => {
            const subsidizerAccount = new commonpbv4.SolanaAccountId();
            subsidizerAccount.setValue(subsidizer);
            const tokenAccount = new commonpbv4.SolanaAccountId();
            tokenAccount.setValue(token);
            const tokenProgramAccount = new commonpbv4.SolanaAccountId();
            tokenProgramAccount.setValue(TOKEN_PROGRAM_ID.toBuffer());

            const resp = new transactionpbv4.GetServiceConfigResponse();
            resp.setSubsidizerAccount(subsidizerAccount);
            resp.setToken(tokenAccount);
            resp.setTokenProgram(tokenProgramAccount);

            const err = validateHeaders(md);
            if (err !== undefined) {
                callback(err, undefined);
                return;
            }

            callback(undefined, resp);
        });
}
Example #2
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 #3
Source File: internal.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test('createAccount', async () => {
    const account = PrivateKey.random();
    const tokenAccount = await Token.getAssociatedTokenAddress(ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, new PublicKey(token).solanaKey(), account.publicKey().solanaKey());

    const env = newTestEnv();
    const [client, accountClientV4, txClientV4] = [env.client, env.accountClientV4, env.txClientV4];

    setGetServiceConfigResp(txClientV4);
    setGetRecentBlockhashResp(txClientV4);

    let created = false;
    when(accountClientV4.createAccount(anything(), anything(), anything()))
        .thenCall((req: accountpbv4.CreateAccountRequest, md: grpc.Metadata, callback) => {
            const err = validateHeaders(md);
            if (err != undefined) {
                callback(err, undefined);
                return;
            }

            const resp = new accountpbv4.CreateAccountResponse();
            if (created) {
                resp.setResult(accountpbv4.CreateAccountResponse.Result.EXISTS);
            } else {
                const tx = SolanaTransaction.from(req.getTransaction()!.getValue_asU8());
                expect(tx.signatures).toHaveLength(2);
                expect(tx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
                expect(tx.signatures[0].signature).toBeNull();

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

                expect(tx.instructions).toHaveLength(2);

                const createAssocInstruction = TokenInstruction.decodeCreateAssociatedAccount(tx.instructions[0]);
                expect(createAssocInstruction.subsidizer.toBuffer()).toEqual(subsidizer);
                expect(createAssocInstruction.address).toEqual(tokenAccount);
                expect(createAssocInstruction.owner.toBuffer()).toEqual(account.publicKey().buffer);
                expect(createAssocInstruction.mint.toBuffer()).toEqual(token);

                const setAuthInstruction = TokenInstruction.decodeSetAuthority(tx.instructions[1]);
                expect(setAuthInstruction.account).toEqual(tokenAccount);
                expect(setAuthInstruction.currentAuthority.toBuffer()).toEqual(account.publicKey().buffer);
                expect(setAuthInstruction.newAuthority!.toBuffer()).toEqual(subsidizer);
                expect(setAuthInstruction.authorityType).toEqual('CloseAccount');

                resp.setResult(accountpbv4.CreateAccountResponse.Result.OK);
                created = true;
            }
            callback(undefined, resp);
        });

    await client.createAccount(account);
    expect(created).toBeTruthy();

    try {
        await client.createAccount(account);
        fail();
    } catch (err) {
        expect(err).toBeInstanceOf(AccountExists);
    }
});
Example #4
Source File: input.directive.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgInputDirective', () => {
  let fixture: ComponentFixture<TestInputComponent>;
  let component: TestInputComponent;
  let inputDebugElement: DebugElement;
  let inputInstance: LgInputDirective;
  const errorStateMatcherMock = mock(LgErrorStateMatcher);

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [ FormsModule, ReactiveFormsModule ],
        declarations: [ LgInputDirective, TestInputComponent ],
        providers: [
          {
            provide: LgErrorStateMatcher,
            useFactory: () => instance(errorStateMatcherMock),
          },
        ],
      }).compileComponents();

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

      inputDebugElement = fixture.debugElement.query(By.directive(LgInputDirective));

      inputInstance = inputDebugElement.injector.get<LgInputDirective>(LgInputDirective);
    }),
  );

  it('adds a unique name', () => {
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.name).toContain('lg-input-');
  });

  it('adds a unique id', () => {
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.id).toContain('lg-input-');
  });

  it('adds a block class when the block property is set', () => {
    inputInstance.block = true;
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.className).toContain('lg-input--block');
  });

  it('adds an error class when the field has a validation error', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.className).toContain('lg-input--error');
  });

  it('removes the error class when the field is valid', () => {
    component.form.get('name').setValue('test');
    component.form.get('name').markAsTouched();

    expect(inputDebugElement.nativeElement.className).not.toContain('lg-input--error');
  });
});
Example #5
Source File: internal.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test('submitTransaction failed', async () => {
    const env = newTestEnv();
    const subsidizer = PrivateKey.random();
    const [client, txClientV4] = [env.client, env.txClientV4];
    const [sender, destination] = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];

    const tx = new SolanaTransaction({
        feePayer: subsidizer.publicKey().solanaKey(),
        recentBlockhash: new PublicKey(recentBlockhash).toBase58(),
    }).add(
        Token.createTransferInstruction(
            TOKEN_PROGRAM_ID,
            sender.solanaKey(),
            destination.solanaKey(),
            sender.solanaKey(),
            [],
            100,
        )
    );
    tx.sign(new SolanaAccount(subsidizer.secretKey()));
    const sig = tx.signature!;

    when(txClientV4.submitTransaction(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const txSig = new commonpbv4.TransactionSignature();
            txSig.setValue(sig);

            const txError = new commonpbv4.TransactionError();
            txError.setReason(commonpbv4.TransactionError.Reason.BAD_NONCE);

            const resp = new transactionpbv4.SubmitTransactionResponse();
            resp.setSignature(txSig);
            resp.setResult(transactionpbv4.SubmitTransactionResponse.Result.FAILED);
            resp.setTransactionError(txError);

            callback(undefined, resp);
        });

    const resp = await client.submitTransaction(tx);
    expect(resp.TxId).toStrictEqual(sig);
    expect(resp.InvoiceErrors).toBeUndefined();
    expect(resp.Errors?.OpErrors![0]).toBeInstanceOf(BadNonce);
});
Example #6
Source File: modal-trigger.directive.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgModalTriggerComponent', () => {
  let fixture: ComponentFixture<TestTriggerComponent>;
  let triggerDebugElement: DebugElement;
  let triggerInstance: LgModalTriggerDirective;
  let modalServiceMock: LgModalService;
  let focusSpy: jasmine.Spy;
  const isOpen$ = new BehaviorSubject(true);

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

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

      when(modalServiceMock.isOpen$(anything())).thenReturn(isOpen$);

      fixture = TestBed.createComponent(TestTriggerComponent);

      triggerDebugElement = fixture.debugElement.query(
        By.directive(LgModalTriggerDirective),
      );

      triggerInstance = triggerDebugElement.injector.get<LgModalTriggerDirective>(
        LgModalTriggerDirective,
      );

      focusSpy = spyOn(triggerDebugElement.nativeElement, 'focus');

      fixture.detectChanges();
    }),
  );

  it('should open the modal on click of the trigger element', () => {
    const clickedSpy = spyOn(triggerInstance.clicked, 'emit');

    triggerDebugElement.nativeElement.click();

    expect(triggerInstance['allowFocusOnModalTrigger']).toBeTrue();
    verify(modalServiceMock.open('test')).once();

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

  it('should set the focus on the trigger when the modal is closed', () => {
    triggerInstance['allowFocusOnModalTrigger'] = true;
    isOpen$.next(false);

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

  it('shouldn\'t set the focus on the trigger when the modal is open', () => {
    triggerInstance['allowFocusOnModalTrigger'] = true;
    isOpen$.next(true);

    expect(focusSpy).toHaveBeenCalledTimes(0);
  });

  it('shouldn\'t set the focus on the trigger if the modal has just been initialised', () => {
    triggerInstance['allowFocusOnModalTrigger'] = false;
    isOpen$.next(false);

    expect(focusSpy).toHaveBeenCalledTimes(0);
  });
});
Example #7
Source File: internal.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test('submitTransaction already submitted', async () => {
    const env = newTestEnv();
    const subsidizer = PrivateKey.random();
    const [client, txClientV4] = [env.client, env.txClientV4];
    const [sender, destination] = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];

    const tx = new SolanaTransaction({
        feePayer: subsidizer.publicKey().solanaKey(),
        recentBlockhash: new PublicKey(recentBlockhash).toBase58(),
    }).add(
        Token.createTransferInstruction(
            TOKEN_PROGRAM_ID,
            sender.solanaKey(),
            destination.solanaKey(),
            sender.solanaKey(),
            [],
            100,
        )
    );
    tx.sign(new SolanaAccount(subsidizer.secretKey()));
    const sig = tx.signature!;

    when(txClientV4.submitTransaction(anything(), anything(), anything()))
        .thenCall((req: transactionpbv4.SubmitTransactionRequest, md: grpc.Metadata, callback) => {
            const txSig = new commonpbv4.TransactionSignature();
            txSig.setValue(sig);

            const resp = new transactionpbv4.SubmitTransactionResponse();
            resp.setResult(transactionpbv4.SubmitTransactionResponse.Result.ALREADY_SUBMITTED);
            resp.setSignature(txSig);

            callback(undefined, resp);
        });

    try {
        await client.submitTransaction(tx);
        fail();
    } catch (error) {
        expect(error).toBeInstanceOf(AlreadySubmitted);
    }

    reset(txClientV4);

    let attempt = 0;
    when(txClientV4.submitTransaction(anything(), anything(), anything()))
        .thenCall((req: transactionpbv4.SubmitTransactionRequest, md: grpc.Metadata, callback) => {
            attempt = attempt + 1;

            if (attempt == 1) {
                const err: grpc.ServiceError = {
                    name: "",
                    message: "",
                    code: grpc.status.INTERNAL,
                };
                callback(err, new transactionpbv4.SubmitTransactionResponse());
                return;
            } else {
                const txSig = new commonpbv4.TransactionSignature();
                txSig.setValue(sig);

                const resp = new transactionpbv4.SubmitTransactionResponse();
                resp.setResult(transactionpbv4.SubmitTransactionResponse.Result.ALREADY_SUBMITTED);
                resp.setSignature(txSig);

                callback(undefined, resp);
            }
        });

    const result = await client.submitTransaction(tx);
    expect(result.TxId).toStrictEqual(sig);
    expect(result.InvoiceErrors).toBeUndefined();
    expect(result.Errors).toBeUndefined();
});
Example #8
Source File: select.directive.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgSelectDirective', () => {
  let fixture: ComponentFixture<TestSelectComponent>;
  let component: TestSelectComponent;
  let selectDebugElement: DebugElement;
  const errorStateMatcherMock = mock(LgErrorStateMatcher);

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [ FormsModule, ReactiveFormsModule ],
        declarations: [ LgSelectDirective, TestSelectComponent ],
        providers: [
          {
            provide: LgErrorStateMatcher,
            useFactory: () => instance(errorStateMatcherMock),
          },
        ],
      }).compileComponents();

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

      selectDebugElement = fixture.debugElement.query(By.directive(LgSelectDirective));
    }),
  );

  it('adds a unique name', () => {
    fixture.detectChanges();

    expect(selectDebugElement.nativeElement.name).toContain('lg-select-');
  });

  it('adds a unique id', () => {
    fixture.detectChanges();

    expect(selectDebugElement.nativeElement.id).toContain('lg-select-');
  });

  it('adds an error class when the field has a validation error', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();

    expect(selectDebugElement.nativeElement.className).toContain('lg-select--error');
  });

  it('removes the error class when the field is valid', () => {
    component.form.get('name').setValue('test');
    component.form.get('name').markAsTouched();

    expect(selectDebugElement.nativeElement.className).not.toContain('lg-input--error');
  });
});
Example #9
Source File: internal.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test('submitTransaction', async () => {
    const env = newTestEnv();
    const subsidizer = PrivateKey.random();
    const [client, txClientV4] = [env.client, env.txClientV4];
    const [sender, destination] = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];

    const tx = new SolanaTransaction({
        feePayer: subsidizer.publicKey().solanaKey(),
        recentBlockhash: new PublicKey(recentBlockhash).toBase58(),
    }).add(
        Token.createTransferInstruction(
            TOKEN_PROGRAM_ID,
            sender.solanaKey(),
            destination.solanaKey(),
            sender.solanaKey(),
            [],
            100,
        )
    );
    tx.sign(new SolanaAccount(subsidizer.secretKey()));
    const sig = tx.signature!;

    let invoiceList: commonpb.InvoiceList | undefined = undefined;
    let commitment: commonpbv4.Commitment = commonpbv4.Commitment.SINGLE;
    let expectedDedupeId: Buffer | undefined = undefined;

    when(txClientV4.submitTransaction(anything(), anything(), anything()))
        .thenCall((req: transactionpbv4.SubmitTransactionRequest, md: grpc.Metadata, callback) => {
            const err = validateHeaders(md);
            if (err != undefined) {
                callback(err, undefined);
                return;
            }

            // Validate request
            expect(Buffer.from(req.getTransaction()!.getValue_asU8())).toStrictEqual(tx.serialize({
                requireAllSignatures: false,
                verifySignatures: false,
            }));
            expect(req.getInvoiceList()).toBe(invoiceList);
            if (expectedDedupeId) {
                expect(Buffer.from(req.getDedupeId())).toEqual(expectedDedupeId);
            } else {
                expect(req.getDedupeId()).toEqual("");
            }
            expect(req.getCommitment()).toEqual(commitment);

            const txSig = new commonpbv4.TransactionSignature();
            txSig.setValue(sig);

            const resp = new transactionpbv4.SubmitTransactionResponse();
            resp.setResult(transactionpbv4.SubmitTransactionResponse.Result.OK);
            resp.setSignature(txSig);

            callback(undefined, resp);
        });

    let result = await client.submitTransaction(tx);
    expect(result.TxId).toStrictEqual(sig);
    expect(result.InvoiceErrors).toBeUndefined();
    expect(result.Errors).toBeUndefined();

    invoiceList = new commonpb.InvoiceList();
    invoiceList.addInvoices(invoiceToProto({
        Items: [
            {
                title: "hello",
                description: "world",
                amount: new BigNumber(10),
            },
        ]
    }));

    result = await client.submitTransaction(tx, invoiceList);
    expect(result.TxId).toStrictEqual(sig);
    expect(result.InvoiceErrors).toBeUndefined();
    expect(result.Errors).toBeUndefined();

    // Submit with all options
    expectedDedupeId = Buffer.from(uuidv4());
    commitment = commonpbv4.Commitment.MAX;
    result = await client.submitTransaction(tx, invoiceList, Commitment.Max, expectedDedupeId);

    expect(result.TxId).toStrictEqual(sig);
    expect(result.InvoiceErrors).toBeUndefined();
    expect(result.Errors).toBeUndefined();
});
Example #10
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 #11
Source File: internal.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test('internal retry Kin 4', async () => {
    let env = newTestEnv();
    const [accountClientV4, airdropClientV4] = [env.accountClientV4, env.airdropClientV4];
    let [client, txClientV4] = [env.client, env.txClientV4];

    const account = PrivateKey.random();
    when(accountClientV4.createAccount(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new accountpbv4.CreateAccountRequest());
        });
    when(accountClientV4.getAccountInfo(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new accountpbv4.GetAccountInfoResponse());
        });
    when(airdropClientV4.requestAirdrop(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new airdroppbv4.RequestAirdropResponse());
        });
    when(txClientV4.getTransaction(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.GetTransactionResponse());
        });
    when(txClientV4.submitTransaction(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.SubmitTransactionResponse());
        });

    setGetServiceConfigResp(txClientV4);
    setGetMinBalanceResp(txClientV4);
    setGetRecentBlockhashResp(txClientV4);

    try {
        await client.createAccount(account);
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(accountClientV4.createAccount(anything(), anything(), anything())).times(3);

    try {
        await client.getAccountInfo(new PublicKey(Buffer.alloc(32)));
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(accountClientV4.createAccount(anything(), anything(), anything())).times(3);

    try {
        await client.getTransaction(Buffer.alloc(32));
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getTransaction(anything(), anything(), anything())).times(3);

    const transaction = new SolanaTransaction({
        feePayer: PrivateKey.random().publicKey().solanaKey(),
        recentBlockhash: new PublicKey(recentBlockhash).toBase58(),
    }).add(
        Token.createTransferInstruction(
            TOKEN_PROGRAM_ID,
            PrivateKey.random().publicKey().solanaKey(),
            PrivateKey.random().publicKey().solanaKey(),
            PrivateKey.random().publicKey().solanaKey(),
            [],
            100,
        )
    );
    try {
        await client.submitTransaction(transaction);
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.submitTransaction(anything(), anything(), anything())).times(3);

    try {
        await client.requestAirdrop(account.publicKey(), new BigNumber(10));
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(airdropClientV4.requestAirdrop(anything(), anything(), anything())).times(3);

    env = newTestEnv();
    client = env.client;
    txClientV4 = env.txClientV4;

    when(txClientV4.getServiceConfig(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.SubmitTransactionResponse());
        });

    when(txClientV4.getRecentBlockhash(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.GetRecentBlockhashResponse());
        });

    when(txClientV4.getMinimumBalanceForRentExemption(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.GetMinimumBalanceForRentExemptionResponse());
        });

    try {
        await client.getServiceConfig();
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getServiceConfig(anything(), anything(), anything())).times(3);

    try {
        await client.getRecentBlockhash();
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getRecentBlockhash(anything(), anything(), anything())).times(3);

    try {
        await client.getMinimumBalanceForRentExemption();
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getMinimumBalanceForRentExemption(anything(), anything(), anything())).times(3);
});
Example #12
Source File: modal.component.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgModalComponent', () => {
  let component: LgModalComponent;
  let cdrMock: ChangeDetectorRef;
  let fixture: MockedComponentFixture<LgModalComponent>;
  let modalServiceMock: LgModalService;
  const id = 'test-1';
  const isModalOpen$ = new BehaviorSubject<boolean>(false);

  beforeEach(
    waitForAsync(() => {
      cdrMock = mock(ChangeDetectorRef);
      modalServiceMock = mock(LgModalService);

      TestBed.configureTestingModule({
        declarations: [
          LgModalComponent,
          MockComponents(LgModalHeaderComponent, LgModalBodyComponent),
        ],
        imports: [ MockModule(LgCardModule), MockModule(LgFocusModule) ],
        providers: [
          { provide: LgModalService, useValue: instance(modalServiceMock) },
          { provide: ChangeDetectorRef, useValue: instance(cdrMock) },
        ],
      }).compileComponents();

      when(modalServiceMock.isOpen$(anything())).thenReturn(isModalOpen$);
    }),
  );

  beforeEach(() => {
    fixture = MockRender(`
      <lg-modal [id]="id">
        <lg-modal-header></lg-modal-header>
        <lg-modal-body></lg-modal-body>
      </lg-modal>
    `);

    component = fixture.debugElement.children[0].componentInstance;
    component.id = id;
    fixture.detectChanges();
  });

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

  describe('on init', () => {
    it('should update isOpen', () => {
      isModalOpen$.next(true);

      expect(component.isOpen).toBe(true);
    });

    it('should add the overflow style to the body and emit an open event if the modal is open', () => {
      const openEmitterSpy = spy(component.open);

      isModalOpen$.next(true);

      verify(openEmitterSpy.emit()).once();

      fixture.detectChanges();
      const bodyEl: HTMLBodyElement = document.querySelector('body');

      expect(bodyEl.style.overflow).toEqual('hidden');
    });

    it('should remove the overflow style on the body and emit a closed event if the modal is close', () => {
      const closedEmitterSpy = spy(component.closed);

      isModalOpen$.next(false);

      verify(closedEmitterSpy.emit()).once();

      fixture.detectChanges();
      const bodyEl: HTMLBodyElement = document.querySelector('body');

      expect(bodyEl.style.overflow).toEqual('');
    });

    it('should detect changes', () => {
      const cdrDetectChangesSpy = spyOn(component['cdr'], 'detectChanges');

      isModalOpen$.next(true);

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

  it('should update the modal header and body id on #ngAfterContentInit', () => {
    component.ngAfterContentInit();

    expect(component.modalHeaderComponent.id).toEqual('lg-modal-header-test-1');
    expect(component.modalBodyComponent.id).toEqual('lg-modal-body-test-1');
  });

  describe('on keydown', () => {
    const escEvent = new KeyboardEvent('keydown', {
      key: keyName.KEY_ESCAPE,
    });

    it('should close the modal when escape key is pressed and the modal is open', () => {
      component.isOpen = true;
      component.onKeydown(escEvent);

      verify(modalServiceMock.close(id)).once();

      expect().nothing();
    });

    it('shouldn\'t close the modal when any other key is pressed', () => {
      component.isOpen = true;
      const event = new KeyboardEvent('keydown', {
        key: keyName.KEY_UP,
      });

      component.onKeydown(event);

      verify(modalServiceMock.close(id)).never();

      expect().nothing();
    });

    it('shouldn\'t close the modal when the modal is already closed', () => {
      component.isOpen = false;
      component.onKeydown(escEvent);

      verify(modalServiceMock.close(id)).never();

      expect().nothing();
    });
  });

  describe('clicking on the modal panel', () => {
    it('should stop the propagation of the event', () => {
      const event = new Event('click');

      spyOn(event, 'stopPropagation').and.callThrough();
      component.onModalClick(event);

      expect(event.stopPropagation).toHaveBeenCalledTimes(1);
    });
  });
});
Example #13
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 #14
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 #15
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 #16
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitEarnBatch with preferred account resolution", async() => {
    const internal = mock(InternalClient);

    const appSubsidizer = PrivateKey.random();
    const sender = PrivateKey.random();
    const resolvedSender = PrivateKey.random();
    const resolvedAccounts = new Map<string, PublicKey>([
        [sender.publicKey().toBase58(), resolvedSender.publicKey()],
    ]);
    
    const originalDests: PublicKey[] = [];
    const resolvedDests: PublicKey[] = [];
    
    const earnCount = 15;
    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),
        };
        originalDests.push(dest.publicKey());
        
        const resolvedDest = PrivateKey.random().publicKey();
        resolvedDests.push(resolvedDest);
        resolvedAccounts.set(dest.publicKey().toBase58(), resolvedDest);
    }

    interface submitRequest {
        tx: Transaction,
        invoiceList?: 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, invoiceList: invoice, commitment, dedupeId});

            if (!attemptedSubmission) {
                attemptedSubmission = true;
                return Promise.resolve({
                    TxId: tx.signature!,
                    Errors: {
                        TxError: new AccountDoesNotExist(),
                    },
                });
            } else {
                attemptedSubmission = false;  // reset for next request
                return Promise.resolve({
                    TxId: tx.signature!,
                });
            }
        });

    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 client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });

    const result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
        subsidizer: appSubsidizer,
    });
    
    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(requests).toHaveLength(2);
    for (let reqId = 0; reqId < requests.length; reqId++) {
        const batchIndex = Math.floor(reqId / 2);
        const resolved = (reqId % 2) == 1;
        
        const req = requests[reqId];
        const tx = req.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]);    
            
            if (resolved) {
                expect(tokenInstruction.source.toBuffer()).toEqual(resolvedSender.publicKey().buffer);
                expect(tokenInstruction.dest.toBuffer()).toEqual(resolvedDests[batchIndex * 18 + i].buffer);
            } else {
                expect(tokenInstruction.source.toBuffer()).toEqual(sender.publicKey().buffer);
                expect(tokenInstruction.dest.toBuffer()).toEqual(originalDests[batchIndex * 18 + i].buffer);
            }
            
            expect(tokenInstruction.owner.toBuffer()).toEqual(sender.publicKey().buffer);
            expect(tokenInstruction.amount).toEqual(BigInt((batchIndex * 18 + i + 1)));
        }
    }
});
Example #17
Source File: c-copy.test.ts    From bindable with MIT License 4 votes vote down vote up
describe('c-copy component', () => {
    let component;
    let mockedNotification: CToastsService;

    describe('Unit', () => {
        afterEach(() => {
            jest.useRealTimers();
        });

        beforeEach(() => {
            jest.useFakeTimers();
            jest.clearAllMocks();

            mockedNotification = mock(CToastsService);
            component = new CCopy(instance(mockedNotification));
        });

        describe('#copy', () => {
            test('without action callback', async () => {
                await component.copy('test');

                verify(mockedNotification.success(anything())).once();
            });

            test('with action callback', async () => {
                component.action = jest.fn(async () => 'Success');

                expect(component.action).toBeDefined();

                await component.copy('***');

                expect(component.action).toHaveBeenCalled();

                verify(mockedNotification.success(anything())).once();
            });
        });
    });

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

        beforeEach(() => {
            jest.clearAllMocks();
        });

        it('testing link enabled', async done => {
            component = StageComponent.withResources()
                .inView('<c-copy link.bind="customLink"></c-copy>')
                .boundTo({
                    customLink: true,
                });

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

        it('testing link to be false if invalid type', async done => {
            component = StageComponent.withResources()
                .inView('<c-copy link.bind="customLink"></c-copy>')
                .boundTo({
                    customLink: 1,
                });

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

        it('testing wrap enabled', async done => {
            component = StageComponent.withResources()
                .inView('<c-copy wrap.bind="customWrap"></c-copy>')
                .boundTo({
                    customWrap: true,
                });

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

        it('testing wrap to be false if invalid type', async done => {
            component = StageComponent.withResources()
                .inView('<c-copy wrap.bind="customWrap"></c-copy>')
                .boundTo({
                    customWrap: 1,
                });

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

        it('tests if copy text link works', async done => {
            const queryStr = 'c-button';
            component = StageComponent.withResources()
                .inView('<c-copy link.bind="customLink"></c-copy>')
                .boundTo({
                    customLink: true,
                });

            try {
                await bootStrapEnvironment(component);
                (document.querySelector(queryStr) as any).click();
                expect(copyToClipboard).toHaveBeenCalledTimes(1);
                expect(component.viewModel.link).toBe(true);
                done();
            } catch (e) {
                done.fail(e);
            }
        });

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

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

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

                try {
                    await bootStrapEnvironment(component);
                    expect(component.viewModel.styles.container).not.toBe(undefined);
                    done();
                } catch (e) {
                    done.fail(e);
                }
            });
        });
    });
});
Example #18
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("mergeTokenAccounts", async() => {
    const internal = mock(InternalClient);
    const client = new Client(Environment.Test, {
        appIndex: 0,
        internal: instance(internal),
    });

    const appSubsidizer = PrivateKey.random();
    const priv = PrivateKey.random();
    
    const ownerId = new commonpbv4.SolanaAccountId();
    ownerId.setValue(priv.publicKey().buffer);

    const closeAuthId = new commonpbv4.SolanaAccountId();
    
    // No accounts to merge
    when(internal.resolveTokenAccounts(anything(), anything()))
    .thenCall(() => {
        return Promise.resolve([]);
    });
    
    let txId = await client.mergeTokenAccounts(priv, false);
    expect(txId).toBeUndefined();
    
    // One resolved account, no create assoc
    let resolvedKeys = [PrivateKey.random().publicKey()];
    let infos: accountpbv4.AccountInfo[] = [];
    
    setGetServiceConfigResp(internal);
    when(internal.resolveTokenAccounts(anything(), anything()))
    .thenCall(() => {
        infos = [];
        resolvedKeys.forEach((key, i) => {
            const id = new commonpbv4.SolanaAccountId();
            id.setValue(key.buffer);
            const info = new accountpbv4.AccountInfo();
            info.setAccountId(id);
            info.setBalance(new BigNumber(1 + i).toString());
            info.setOwner(ownerId);
            info.setCloseAuthority(closeAuthId);
            
            infos.push(info);    
        });
        return Promise.resolve(infos);
    });
    
    txId = await client.mergeTokenAccounts(priv, false);
    expect(txId).toBeUndefined();

    // Multiple accounts
    resolvedKeys = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];
    
    let signReq: signRequest | undefined;
    let submitReq: submitRequest | undefined;
    setGetRecentBlockhashResp(internal);
    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: il, commitment, dedupeId};
            const result = new SubmitTransactionResult();
            result.TxId = tx.signature!;
            return Promise.resolve(result);
        });

    interface testCase {
        createAssoc: boolean;
        subsidizer?: PrivateKey;
        shouldClose: boolean;
    }

    const tcs: testCase[] = [
        {
            createAssoc: false,
            shouldClose: false,
        },
        {
            createAssoc: true,
            shouldClose: false,
        },
        {
            createAssoc: false,
            subsidizer: appSubsidizer,
            shouldClose: false,
        },
        {
            createAssoc: true,
            subsidizer: appSubsidizer,
            shouldClose: false,
        },
        {
            createAssoc: false,
            shouldClose: true,

        },
    ];

    for (const tc of tcs) {
        signReq = undefined;
        submitReq = undefined;
        
        if (tc.shouldClose) {
            if (tc.subsidizer) {
                closeAuthId.setValue(tc.subsidizer.publicKey().buffer);
            } else {
                closeAuthId.setValue(subsidizer);
            }
        } else {
            closeAuthId.setValue('');
        }

        txId = await client.mergeTokenAccounts(priv, tc.createAssoc, Commitment.Single, tc.subsidizer);
        expect(txId).toBeDefined();

        if (tc.subsidizer) {
            expect(signReq).toBeUndefined();
            expect(submitReq).toBeDefined();

            const submitTx = submitReq!.tx;
            expect(submitTx.signatures).toHaveLength(2);
            expect(submitTx.signatures[0].publicKey.toBuffer()).toEqual(tc.subsidizer.publicKey().buffer);
            expect(tc.subsidizer.kp.verify(submitTx.serializeMessage(), submitTx.signatures[0].signature!)).toBeTruthy();
            expect(submitTx.signatures[1].publicKey.toBuffer()).toEqual(priv.publicKey().buffer);
            expect(priv.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();
            await assertMergeTx(submitTx, priv, infos, tc.createAssoc, tc.shouldClose, Buffer.from(closeAuthId.getValue_asU8()), tc.subsidizer);

            // The returned txId should be the one in the submit request
            expect(txId!.equals(submitTx.signature!)).toBeTruthy();
        } else {
            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(priv.publicKey().buffer);
            expect(priv.kp.verify(signTx.serializeMessage(), signTx.signatures[1].signature!)).toBeTruthy();
            await assertMergeTx(signTx, priv, infos, tc.createAssoc, tc.shouldClose, Buffer.from(closeAuthId.getValue_asU8()));
            
            expect(submitReq).toBeDefined();

            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(priv.publicKey().buffer);
            expect(priv.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();

            expect(submitTx.serializeMessage().equals(signTx.serializeMessage())).toBeTruthy();

            // The returned txId should be the one in the submit request
            expect(txId!.equals(submitTx.signature!)).toBeTruthy();
        }
    }
});