How to use the chance.Chance function in chance

To help you get started, we’ve selected a few chance examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rintoj / ngx-virtual-scroller / demo / src / app / lists / base-list.ts View on Github external
{
	  return this._items;
  }
  public set items(value: ListItem[])
  {
	  this._items = value;
	  this.setToFullList();
  }

  public ListItemComponent = ListItemComponent;
  public randomSize = false;

  public filteredList: ListItem[];

  public static index = 0;
  public static chance = new Chance(0); // 0 = seed for repeatability
  public static generateRandomItem(): ListItem {
	  return {
		  id: BaseList.chance.guid(),
		  index: BaseList.index++,
		  name: BaseList.chance.name(),
		  gender: BaseList.chance.gender(),
		  age: BaseList.chance.age(),
		  email: BaseList.chance.email(),
		  phone: BaseList.chance.phone(),
		  address: BaseList.chance.address() + ', ' + BaseList.chance.city() + ', ' + BaseList.chance.state() + ', ' + BaseList.chance.zip(),
		  company: BaseList.chance.company()
	  };
  }
  
  public static generateMultipleRandomItems(count: number): ListItem[] {
	  let result = Array(count);
github mozilla / fxa / packages / fxa-event-broker / bin / generate-sqs-traffix.ts View on Github external
import Config from '../config';
import { ClientCapabilityService } from '../lib/selfUpdatingService/clientCapabilityService';
import { FactoryBot, LoginEvent, SubscriptionEvent } from '../test/service-notifications';

AWS.config.update({
  region: 'us-east-1'
});

/** Total messages to generate before stopping.
 * @constant {number}
 * @default
 */
const MESSAGE_COUNT = 10_000;

const chance = new Chance();

const sqs = new SQS();
const queueUrl = Config.get('serviceNotificationQueueUrl');
const logger = mozlog(Config.get('log'))('generate-sqs-traffic');

// Promisify the AWS send message, the Node promisify mangled the TS signature
const sqsSendMessage = (params: SQS.SendMessageRequest): Promise =>
  new Promise((resolve, reject) => {
    sqs.sendMessage(params, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
github balassy / aws-lambda-typescript / src / cities / cities.service.spec.ts View on Github external
import { expect } from 'chai';
import { Chance } from 'chance';
import { instance, mock, reset, when } from 'ts-mockito';

import { ErrorResult, ForbiddenResult, NotFoundResult } from '../../shared/errors';
import { City, GetCityResult } from './cities.interfaces';
import { CitiesRepository } from './cities.repository';
import { CitiesService } from './cities.service';

// tslint:disable no-unsafe-any (Generates false alarm with ts-mockito functions.)

const chance: Chance.Chance = new Chance();

describe('CitiesService', () => {
  const citiesRepositoryMock: CitiesRepository = mock(CitiesRepository);
  const citiesRepositoryMockInstance: CitiesRepository = instance(citiesRepositoryMock);
  let service: CitiesService;
  let testCity: City;

  beforeEach(() => {
    reset(citiesRepositoryMock);
    service = new CitiesService(citiesRepositoryMockInstance, process.env);
    testCity = {
      country: chance.country(),
      id: chance.natural(),
      name: chance.city(),
      populationDensity: chance.natural()
    };
github UXAspects / UXAspects / docs / app / pages / components / components-sections / notifications / notification-list-ng1 / wrapper / notification-list-wrapper.directive.ts View on Github external
function NotificationListDemoModalCtrl($q: ng.IQService, $scope: ng.IScope, safeTimeout: any, timeAgoService: any) {
    var vm = this;

    var chance = require('chance').Chance();

    // create safe timeout instance
    var safeTimeoutInstance = safeTimeout.create($scope);

    vm.itemTemplateUrl = 'notification-list-ng1/notification.html';

    vm.getPage = function (pageNumber: number, pageSize: number) {
        // return promise to simulate loading from a server
        var defer = $q.defer();

        safeTimeoutInstance.timeout(function () {

            // generate some fake notifications here
            var notifications = [];

            // show a maximimum of 10 pages
github working-minds / realizejs / test / specs / grid / grid.spec.js View on Github external
describe('', () => {
  const dummyUrl = '';
  const chance = new Chance();
  let sandbox;

  beforeEach(() => sandbox = sinon.sandbox.create());
  afterEach(() => sandbox.restore());

  describe('#constructor', () => {
    it('is a component', () => expect(Grid).to.be.a.reactComponent);
  });

  describe('#componentDidMount', () => {
    it('calls loadData when the props eagerLoad is true', () => {
      const loadData = sinon.stub(Grid.prototype, 'loadData');
      const withEagerLoad = mount();

      expect(withEagerLoad).to.be.ok;
      expect(loadData).to.have.been.calledOnce;
github stoplightio / prism / packages / http / src / mocker / negotiator / __tests__ / HttpOperationOptionsNegotiator.spec.ts View on Github external
import helpers from '../NegotiatorHelpers';
import HttpOperationConfigNegotiator from '../HttpOperationConfigNegotiator';
import { Chance } from 'chance';
import { anHttpOperation } from '@stoplight/prism-http/mocker/negotiator/__tests__/utils';
import { IValidation, ValidationSeverity } from '@stoplight/prism-core/types';
import { IHttpRequest } from '@stoplight/prism-http/types';

const chance = new Chance();

describe('HttpOperationOptionsNegotiator', () => {
  let negotiator: HttpOperationConfigNegotiator;

  beforeEach(() => {
    negotiator = new HttpOperationConfigNegotiator();
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  describe('negotiate()', () => {
    const httpOperationConfig = {
      code: chance.string(),
      mediaType: chance.string(),
github balassy / aws-lambda-typescript / src / cities / cities.spec.ts View on Github external
import { expect } from 'chai';
import { Chance } from 'chance';

import { HttpStatusCode } from '../../shared/http-status-codes';
import { call } from '../../test';
import { ApiResponseParsed, PathParameter } from '../../test/test.interfaces';
import { getCity } from './cities';
import { GetCityResult } from './cities.interfaces';

const chance: Chance.Chance = new Chance();

describe('Cities handler', () => {
  describe('getCity function', () => {
    describe('success', () => {
      it('should return HTTP 200 OK', async () => {
        await callAndCheckStatusCode('1', HttpStatusCode.Ok);
      });

      it('should return the city from the environment variable', async () => {
        const city: string = chance.city();
        process.env.FAVORITE_CITY = city;
        const pathParameters: PathParameter = {
          id: '1'
        };
        const result: ApiResponseParsed = await call(getCity, pathParameters);
        expect(result.parsedBody.city).to.equal(city);
github subeeshcbabu / swagmock / lib / generators / index.js View on Github external
'use strict';
const Chance = require('chance').Chance();
const Format = require('./format');
const Randexp = require('randexp').randexp;

const mock = (schema, useExample)  => {
    let mock;
    if (schema) {
        let type = schema.type || findType(schema);
        var example = schema.examples || schema.example;
        /**
         * Get the mock generator from the `type` of the schema
         */
        if (example && useExample) {
            mock = example;
        } else {
            const generator = Generators[type];
            if (generator) {
github UXAspects / UXAspects / docs / app / pages / components / components-sections / scrollbar / infinite-scroll-load-more-ng1 / wrapper / infinite-scroll-load-more-wrapper.directive.ts View on Github external
controller: ['$scope', '$templateCache', '$q', 'safeTimeout', function ($scope, $templateCache, $q, safeTimeout) {
            $templateCache.put('infinite-scroll-load-more-ng1/itemTemplate.html', require('./itemTemplate.html'));

            var chance = require('chance').Chance();

            var vm = this;

            var safeTimeoutInstance = safeTimeout.create($scope);
            var departments = ['Finance', 'Operations', 'Investor Relations', 'Technical', 'Auditing', 'Labs'];

            vm.infiniteScrollbarConfig = {
                resizeSensor: true,
                enableKeyboardNavigation: true
            };

            vm.pageSize = 20;
            vm.scrollPosition = 95;
            vm.containerId = 'user-container';
            vm.itemTemplate = 'infinite-scroll-load-more-ng1/itemTemplate.html';
            vm.loadMoreButton = {
github vitalybe / radio-stream / app / js / app / utils / backend_metadata_api / backend_metadata_api_mock.js View on Github external
import loggerCreator from "app/utils/logger";
const moduleLogger = loggerCreator("backend_metadata_api");

import chanceLib from "chance";
import moment from "moment";
import _ from "lodash";
import mockMp3 from "app/data/mock.mp3";

import sleep from "app/utils/sleep";

const chance = chanceLib.Chance();
const playlistResponse = ["Mock", "Heavy Mock", "Peacemock"];

class BackendMetadataApiMock {
  constructor() {
    this.lastId = 0;
  }

  _mockName() {
    return _.startCase(chance.sentence({ words: chance.integer({ min: 1, max: 3 }) }));
  }

  _mockSongArtistTitle() {
    const songs = [
      { artist: "Crystal Castles", title: "Crimewave" },
      { artist: "David Bowie", title: "Ashes To Ashes" },
      { artist: "Dorothy's Magic Bag", title: "Skaldjursakuten" },

chance

Chance - Utility library to generate anything random

MIT
Latest version published 1 year ago

Package Health Score

76 / 100
Full package analysis