npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mz-mock

v1.0.50

Published

Mock decorator for light debugging and tests

Downloads

45

Readme

Описание

Библиотека c декоратороми для моков и генераторов Подходит для дебагинга и тестирования

Установка
npm i --save mz-mock
Examples use main decorator for work with
  import {MzMock, MzMockObservable, MzMockPromise, MzMockResultTypeEnum, MzMockSimple} from "./@res/mz-mock";
  import {of} from "rxjs";
  
  class Class {
    @MzMockSimple (
      {
        result: 'from simple mock',
        active: true
      }
    )
    private simple (a: any, b: any) {
        return `from result - a = ${a} | b = ${b}`;
    }
    
    /* get value from mock and convert to observable */
    @MzMockObservable (
      {
        result: environment,
        path: 'dev.mock.data',
        active: true
      }
    )
    private mockSampleObservable (a: any, b: any) {
        return of(`from result - a = ${a} | b = ${b}`);
    }
    
    @MzMockPromise (
      {
        result: 'from promise mock',
        active: false
      }
    )
    private mockSamplePromise1 (a: any, b: any) {
        return new Promise(
            (resolve) => {
              resolve(`from promise - a = ${a} | b = ${b}`);
            }
        );
    }
    
    /* return value from function after get it by path from result */
    @MzMockFunction (
      {
        result: envirement,
        path: "mock.logic-add-user",
        active: false
      }
    )
    private mockSamplePromise1 (a: any, b: any) {
        return new Promise(
            (resolve) => {
              resolve(`from promise - a = ${a} | b = ${b}`);
            }
        );
    }
    
    
    @MzMock (
      {
        result: 'from promise MzMock',
        active: true,
        type: MzMockResultTypeEnum.promise
      }
    )
    private mockSamplePromise (a: any, b: any) {
        return new Promise(
            (resolve) => {
              resolve(`from MzMock promise - a = ${a} | b = ${b}`);
            }
        );
    }
    
    @MzMock (
      {
        result: (a, b) => `from function MzMock- a = ${a} | b = ${b}`,
        active: false,
        type: MzMockResultTypeEnum.function
      }
    )
    private mockSampleSimple2 (a: any, b: any) {
        return `from function - a = ${a} | b = ${b}`;
    }
    
    
    /*
    * return mock
    * */
    @MzMock(
      {
          type: MzMockResultTypeEnum.simple,
          path: 'mock.test.a',
          result: {mock: {test: { a: 1}}},
          default: 0,
          active: true
      }
    )
    private testFunction ()
    {
        return 'from real 1';
    }
  }
Test mock with "import" for promise and observable
    import {MzMockObservable, MzMockPromise} from "./@res/mz-mock";
    import {Observable, of} from "rxjs";
    
    class TestImportForObservableAndPromise {
        @MzMockObservable({
            path: 'mock',
            storage: () => import('./test4'),
            default: null,
            active: false,
        })
        // @ts-ignore
        testMockObservable (): Observable<any> {
            return of({fromMethod: 'testMockObservable'})
        }
    
        @MzMockPromise({
            path: 'mock',
            storage: () => import('./test4'),
            default: null,
            active: false,
        })
        // @ts-ignore
        async testMockPromise (): Promise<any> {
            return {fromMethod: 'testMockPromise'};
        }
    
        testObservable () {
            this.testMockObservable().subscribe(
                (result) => {
                    console.log(
                        'testObservable - result ',
                        {result}
                    )
                }
            )
        }
    
        async testPromise () {
            const result = await this.testMockPromise();
            console.log(
                'testPromise - result',
                {result}
            );
        }
    }
    
    
    new TestImportForObservableAndPromise().testObservable();
    new TestImportForObservableAndPromise().testPromise();
Add post calback for work with singleton
    // environment.dev.ts
    const testData = {
        valA: 1,
        valB: 2,
    };
    const environment = {
        dev: {
            mock: {
                getTestData: testData
            }
        }
    };   
    
    // test.service.ts (file)
    class TestService {
        /* get value from mock and convert to observable */
        @MzMockObservable (
            {
                result: environment,
                path: 'dev.mock.getTestData',
                post: (a, b) => {
                    
                },
                active: true
            }
        )
        private mockSampleObservable (a: any, b: any) {
            return of(`from result - a = ${a} | b = ${b}`);
        }
    }

#Генераторы

Пример №2 использования генераторов для моков
import {MzMockGenerator} from "mz-mock";

export const names = [
    'Амирхан',
    'Муса',
    'Адам',
    'Сайхан',
    'Абдуллах',
    'Зураб',
    'Тони',
    'Джони деп',
    'Капитан америка',
    'Сайфуллахь',
    'Джарвис',
    'Убайд',
    'Хизир',
    'Муслим',
    'Азнаур',
    'Зина',
    'Залина',
    'Марина',
    'Екатенира',
    'Света',
    'Фатима',
];

const surnames = [
    'Aliev',
    'Magomadov',
    'Abdulaev'
]

const mzMockGenerator = new MzMockGenerator(
    {
        default: names,
        surnames: surnames,
    },
    // кастомные генераторы
    []
);

const testObject = {
    id: 1,
    appsTitle: 'Apps',
    appItems: mzMockGenerator.get<any>(
        {
            /* get random number with default params from 1 to 1000 */
            randomNumber: '__random.number__',
            /* get random number with specific min and max params */
            randomNumberWithMinAndMax: '__random.number(9999, 99999)__',
            /* get index */
            index: '__idx__',
            /* get index with increment 1 */
            number: '__idx(1)__',
            appImg: '__icon__',
            /* get random element from default box */
            appName: '__box__',
            /* get uuid */
            uuid: '__uuid__',
            /* get lorem words (default 1) */
            lorem: '__lorem(2)__',
            /* get lorem sentences  (default 1) */
            loremSentences: '__lorem.sentences(5)__',
            /* get lorem paragraphs  (default 1) */
            loremParagraphs: '__lorem.paragraphs(2)__',
            /* get random element from surnames box */
            surname: '__box(surnames)__',
            /* get random boolean */
            randomBoolean: '__random.bool__',
            testKey: 'abdullakh',
            selected: false,
        },,
        20
    ),
};

Результат примера №2

{
  randomNumber: 225,
  randomNumberWithMinAndMax: 66116,
  index: 0,
  number: 1,
  appImg: 'https://i.pravatar.cc/300?img=30',
  appName: 'Екатенира',
  surname: 'Magomadov',
  testKey: 'abdullakh',
  selected: false
},
{
  randomNumber: 313,
  randomNumberWithMinAndMax: 57895,
  index: 1,
  number: 2,
  appImg: 'https://i.pravatar.cc/300?img=11',
  appName: 'Муслим',
  surname: 'Magomadov',
  testKey: 'abdullakh',
  selected: false
},

Интерфесы для создание кастомного генератора

    export interface MzMockGeneratorCustomInterface {
        key: string;
        get (input: MzMockGeneratorGeneratorInputInterface): any
    }

    export interface MzMockGeneratorGeneratorInputInterface {
        boxes: MzMockGeneratorBoxesInterface,
        idx: number;
        obj: any;
        key: string;
        keyName: any;
        defaultBoxName: string;
        params: string[];
        context: any;
        keyIdx: number;
    }

Пример генератора для работы вывода индекса

    export class MzMockGeneratorIdxService implements MzMockGeneratorCustomInterface {
        key = 'idx';
        get(input: MzMockGeneratorGeneratorInputInterface): any {
            const increment = parseInt(input.params[0] || '0', 10);
            return input.idx + increment;
        }
    }