1.1.5 • Published 6 days ago

@teamteanpm2024/totam-temporibus-odio v1.1.5

Weekly downloads
-
License
MIT
Repository
github
Last release
6 days ago

Mock components, services and more out of annoying dependencies for simplification of Angular testing

@teamteanpm2024/totam-temporibus-odio facilitates Angular testing and helps to:

  • mock Components, Directives, Pipes, Modules, Services and Tokens
  • reduce boilerplate in tests
  • access declarations via simple interface

The current version of the library has been tested and can be used with:

Angular@teamteanpm2024/totam-temporibus-odioJasmineJestIvy
18latestyesyesyes
17latestyesyesyes
16latestyesyesyes
15latestyesyesyes
14latestyesyesyes
13latestyesyesyes
12latestyesyesyes
11latestyesyesyes
10latestyesyesyes
9latestyesyesyes
8latestyesyes
7latestyesyes
6latestyesyes
5latestyesyes

Important links

Very short introduction

Global configuration for mocks in src/test.ts. In case of jest, src/setup-jest.ts / src/test-setup.ts should be used.

// All methods in mock declarations and providers
// will be automatically spied on their creation.
// https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/extra/auto-spy
ngMocks.autoSpy('jasmine'); // or jest

// ngMocks.defaultMock helps to customize mocks
// globally. Therefore, we can avoid copy-pasting
// among tests.
// https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/api/ngMocks/defaultMock
ngMocks.defaultMock(AuthService, () => ({
  isLoggedIn$: EMPTY,
  currentUser$: EMPTY,
}));

An example of a spec for a profile edit component.

// Let's imagine that there is a ProfileComponent
// and it has 3 text fields: email, firstName,
// lastName, and a user can edit them.
// In the following test suite, we would like to
// cover behavior of the component.
describe('profile:builder', () => {
  // Helps to reset customizations after each test.
  // Alternatively, you can enable
  // automatic resetting in test.ts.
  MockInstance.scope();

  // Let's configure TestBed via MockBuilder.
  // The code below says to mock everything in
  // ProfileModule except ProfileComponent and
  // ReactiveFormsModule.
  beforeEach(() => {
    // The result of MockBuilder should be returned.
    // https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/api/MockBuilder
    return MockBuilder(
      ProfileComponent,
      ProfileModule,
    ).keep(ReactiveFormsModule);
    // // or old fashion way
    // return TestBed.configureTestingModule({
    //   imports: [
    //     MockModule(SharedModule), // mock
    //     ReactiveFormsModule, // real
    //   ],
    //   declarations: [
    //     ProfileComponent, // real
    //     MockPipe(CurrencyPipe), // mock
    //     MockDirective(HoverDirective), // mock
    //   ],
    //   providers: [
    //     MockProvider(AuthService), // mock
    //   ],
    // }).compileComponents();
  });

  // A test to ensure that ProfileComponent
  // can be created.
  it('should be created', () => {
    // MockRender is an advanced version of
    // TestBed.createComponent.
    // It respects all lifecycle hooks,
    // onPush change detection, and creates a
    // wrapper component with a template like
    // <app-root ...allInputs></profile>
    // and renders it.
    // It also respects all lifecycle hooks.
    // https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/api/MockRender
    const fixture = MockRender(ProfileComponent);

    expect(
      fixture.point.componentInstance,
    ).toEqual(assertion.any(ProfileComponent));
  });

  // A test to ensure that the component listens
  // on ctrl+s hotkey.
  it('saves on ctrl+s hot key', () => {
    // A fake profile.
    const profile = {
      email: 'test2@email.com',
      firstName: 'testFirst2',
      lastName: 'testLast2',
    };

    // A spy to track save calls.
    // MockInstance helps to configure mock
    // providers, declarations and modules
    // before their initialization and usage.
    // https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/api/MockInstance
    const spySave = MockInstance(
      StorageService,
      'save',
      jasmine.createSpy(), // or jest.fn()
    );

    // Renders <profile [profile]="params.profile">
    // </profile>.
    // https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/api/MockRender
    const { point } = MockRender(
      ProfileComponent,
      { profile }, // bindings
    );

    // Let's change the value of the form control
    // for email addresses with a random value.
    // ngMocks.change finds a related control
    // value accessor and updates it properly.
    // https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/api/ngMocks/change
    ngMocks.change(
      '[name=email]', // css selector
      'test3@em.ail', // an email address
    );

    // Let's ensure that nothing has been called.
    expect(spySave).not.toHaveBeenCalled();

    // Let's assume that there is a host listener
    // for a keyboard combination of ctrl+s,
    // and we want to trigger it.
    // ngMocks.trigger helps to emit events via
    // simple interface.
    // https://@teamteanpm2024/totam-temporibus-odio.sudo.eu/api/ngMocks/trigger
    ngMocks.trigger(point, 'keyup.control.s');

    // The spy should be called with the user
    // and the random email address.
    expect(spySave).toHaveBeenCalledWith({
      email: 'test3@em.ail',
      firstName: profile.firstName,
      lastName: profile.lastName,
    });
  });
});

Profit.

Extra

If you like @teamteanpm2024/totam-temporibus-odio, please support it:

Thank you!

P.S. Feel free to contact us if you need help.

sortedeast-asian-widthsettypescripttyped arrayimportexportSymbolpersistentbyteLengthbindstringifyrapidbundlerfullenvPromiseprivate dataregular expressionrangeerrorserializerES8coreexitES2017Uint8Arraywafworkerpreserve-symlinksminimalfast-cloneasynchooksbalancedlook-upwarningargumentirqCSSreact-testing-libraryESnextfixed-widthquerykeysprefixpropECMAScript 7yupartHyBireduxbufferseslintshimmobileRFC-6455workspace:*typeofreal-timechromeweaksetwalkingprotocol-buffersbuffersignalmiddlewareextendaccessoreveryhigher-orderjsonpathrdstranspilerArray.prototype.findLastIndexfseventsECMAScript 2015callbindpropertiesTypedArrayArray.prototype.findLastjsoffsetUint8ClampedArrayObject.getPrototypeOfObject.keysjsdiffslicefastcopyconfigurabletoArraypopmotionclassnamesfullwidthframervestsyntaxerrorInt8ArraycharacterECMAScript 2018JSONconfigcoerciblees7react-hook-formES2020picomatchless.jshandlersisagentlogiamgetOwnPropertyDescriptorstructuredCloneparentsdayjscurldiffArray.prototype.filterstylingcloudformationastassignec2Symbol.toStringTagweakmapboundrm -frparsetoolstoSortedprivatemulti-packagedropcode pointsiterationincludesjwtes8connectreact posetrimmonorepoelbES7cloudfrontwatchFilegradients cssramdatdddescriptionopenperformantRxArray.prototype.flatMapvalidatorunicodeuninstallObject.assignajvlastqueuetesterclass-validatortestingthroatmomentwrapoptimistReactiveExtensionsnamesfindupmovecomparegradients css3arrayprototypesafea11yconstpathl10ntrimEndES2021hookformcolorprotointrinsicidlepureecmascriptsigtermchaisettingsdescriptors3drandomjsonnoperemovelibphonenumbersomeoutputsuperagentmodulesi18nprotobufes-shim APIfsdeep-copylimitedtestsameValueZerovariablesflatMaplanguageconcatcontainskarmarmelectronairbnbstringifierdirectoryroute53react animationgetopttakejsxassert$.extendless csssuperstructRxJSinstallArray.prototype.containsES2022loggingcall-boundES2016mkdirsstreamscolourfantasy-landURLSearchParamslruFloat32Arrayrequestless mixinsrobustemojijson-schema-validatormacoslinewrapreadwaitdeepcopyebstimeslotglobcorsregexpjsdomspecbannerInt16Arrayinstalleres6bcrypthelperssanitizetypanionautoscalingdataViewconsumebyteOffsetio-tsdependenciesnpmarraysoptimizertrimRightcss-in-jsreadablelessforEachflattenproxyinspectescapereact-hooksuser-streamsprogressstatelesssigintargsextrautilscloudtrailes5yamlisConcatSpreadabledebugvaluebusypasswordbootstrap lessvisualstringtoobjectdatastructuregetterfastifyinferencewidthsearchwordbreakerroroncewebqsieexpressfpformatdom-testing-librarygenericshasdirsespromisetostringtagutil.inspectchinese0ECMAScript 2023requireajaxpackagesletcommandencryptionmapdeepECMAScript 2017parsergroupByes2015efficientzodCSSStyleDeclarationhashES5httpRegExp#flagsregulartc39es2016Uint32ArrayanimationsnststranspilebabelauthsequenceECMAScript 5[[Prototype]]6to5mkdirptypeMicrosoftdeletegetIteratoreslintconfigpyyamlsyntaxinternal slotsharedarraybuffercall-bindrateeslintplugininvarianteslint-pluginflatArray.prototype.flattenkinesisArraymapreduceaccessibilitypolyfilldependency managerloadbalancingstyled-componentsflagnumberString.prototype.trimdataES2015ESshrinkwrapgroupwatchArrayBuffer#sliceFloat64ArrayformnamespeedmimetypesECMAScript 3avaclimixinsposeawsmatchAllmake dirvpc@@toStringTagrgbrecursivefindLastIndexwritableWebSocketsgestureslintmruredacttelephoneasciiutilserializationratelimitwritereactpluginpropertystreams2packagexhrYAMLschemewhichsignalsObject.definePropertyObjectquerystringeventDispatchermkdircollectionES2018nodepatchstylecompilersymlinksmergequeueMicrotaskBigInt64Arrayfast-copynodejsfunctionmakeES6enumerableprettyvaluesimmutablestyleses2017toolkitlimitfind-upauthenticationeventEmitterjson-schema-validationfunctionsstreamcacheInt32ArrayECMAScript 2020clonesymbolbatchutilitieswatchingthrottlecirculargetintrinsicchannelviewspinnersloadingbluebirdemrframeworkObject.fromEntrieswaapidragarraybufferAsyncIteratorstatuskoreanpostcss-pluginnegativeclassescsscss variablecloudsearchassertsupcompile lesscolumnsoperating-systemworkflowcryptswffetchsetPrototypeOflockfileansithreeStreamstslibserializes3ECMAScript 6dateURLsetterextensionpromisesfile systemjapaneseStreamcollection.es6regexutilityequalphoneTypeScriptiterateparenttoStringTagbrowserpusharktypeUint16Arraytapeconcurrencyprocessstylesheetcolorsnegative zerotypeerrorconcatMapesamazonestreemochaes-shimseventspostcssexecnativecolumntypesenderReactiveX_.extendlazysanitizationhasOwntypedarraylinuxomitWeakSetcore-jsObject.istouchinternalpoint-freecloudwatchcryptoRegExp.prototype.flagsArray.prototype.includesECMAScript 2019lookglacierpnpm9watcherless compilershampackage managererror-handlinggetPrototypeOftermreusefilevalidationdefineJSON-Schemaregular expressionsvariables in csskeybundlingloggerdataviewcss nestingpreprocessorvalidateTypeBoxentriesgdprfindsymbolscallbackbreakobj-0environmentmetadataECMAScript 2022package.jsonbootstrap csscallbound__proto__fastclonecreatedynamodbtaskexit-codeiteratorparsingquotesharedtraversehardlinksjestmimeawaitsymlinkWebSocketsimpledbjavascriptECMAScript 2021rfc4122Reflect.getPrototypeOfES3runtimeguidemitcensorObject.entrieschecktextlinkduplexargvassertionbabel-corefilterxssbrowserlistcodesmatchspringfast-deep-copyfull-widthFunction.prototype.nameuuidstyleguide
1.1.5

6 days ago

1.1.4

7 days ago

1.1.3

8 days ago

1.1.2

9 days ago

1.1.1

10 days ago

1.0.1

11 days ago

1.0.0

11 days ago