{"id":13808073,"url":"https://github.com/duluca/angular-unit-test-helper","last_synced_at":"2025-04-12T18:10:27.987Z","repository":{"id":34646031,"uuid":"181814646","full_name":"duluca/angular-unit-test-helper","owner":"duluca","description":"Helper functions to help write unit tests in Angular using mocks and spies","archived":false,"fork":false,"pushed_at":"2023-12-22T07:57:45.000Z","size":669,"stargazers_count":4,"open_issues_count":1,"forks_count":4,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-04-23T20:15:44.655Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/angular-unit-test-helper","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/duluca.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-04-17T04:03:24.000Z","updated_at":"2024-06-13T19:47:33.874Z","dependencies_parsed_at":"2023-11-10T23:22:28.257Z","dependency_job_id":"80962ddb-c0fc-4920-80c4-2f85e5495fc5","html_url":"https://github.com/duluca/angular-unit-test-helper","commit_stats":{"total_commits":96,"total_committers":4,"mean_commits":24.0,"dds":0.07291666666666663,"last_synced_commit":"5d3bf60060cfdcc051f95ded22f208819a0bd814"},"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/duluca%2Fangular-unit-test-helper","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/duluca%2Fangular-unit-test-helper/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/duluca%2Fangular-unit-test-helper/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/duluca%2Fangular-unit-test-helper/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/duluca","download_url":"https://codeload.github.com/duluca/angular-unit-test-helper/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248610338,"owners_count":21132919,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-04T01:01:34.591Z","updated_at":"2025-04-12T18:10:27.951Z","avatar_url":"https://github.com/duluca.png","language":"TypeScript","readme":"# Angular Unit Test Helper\n\n\u003e Helper functions to help write unit tests in Angular using mocks and spies\n\n![Angular Version](https://img.shields.io/badge/angular-v17-326839)\n[![CircleCI](https://circleci.com/gh/duluca/angular-unit-test-helper.svg?style=svg)](https://circleci.com/gh/duluca/angular-unit-test-helper)\n[![Coverage Status](https://coveralls.io/repos/github/duluca/angular-unit-test-helper/badge.svg?branch=main)](https://coveralls.io/github/duluca/angular-unit-test-helper?branch=main)\n\n[![npm](https://img.shields.io/npm/v/angular-unit-test-helper)](https://www.npmjs.com/package/angular-unit-test-helper)\n[![npm](https://img.shields.io/npm/dt/angular-unit-test-helper)](https://www.npmjs.com/package/angular-unit-test-helper)\n\n## Breaking Changes\n\n- `createComponentMock` has been removed, in favor of `ng-mocks`. See below for more info.\n\n## Goal\n\nMinimal feature set to bridge obvious gaps in jasmine's support of modern JavaScript features. Ideally, I'd like to be using an auto-mocking library, but they don't play well with Angular's `TestBed` and `RxJS\\BehaviorSubject`.\n\nHere's a great article about auto-mocking libraries: https://hackernoon.com/with-typescript-3-and-substitute-js-you-are-already-missing-out-when-mocking-or-faking-a3b3240c4607.\n\n## Install\n\nAdd the package to your Angular project with npm:\n\n```bash\nnpm i -D angular-unit-test-helper\n```\n\n## Example Projects\n\nCheck out my sample projects that leverage `angular-unit-test-helper`:\n\n- https://github.com/duluca/local-weather-app\n- https://github.com/duluca/lemon-mart\n\nUse the [`ng-tester`](https://www.npmjs.com/package/ng-tester) package to generate robust and efficient unit tests using `angular-unit-test-helper`.\n\nUsage\n\n```bash\nnpm i -D ng-tester\nnpx ng g ng-tester:unit\n```\n\nFor more information see https://github.com/bjsawyer/ng-tester/.\n\n## Features\n\n### `autoSpyObj(classUnderTest: Function, spyProperties: string[] = [], observableStrategy = ObservablePropertyStrategy.Observable)`\n\nAn extension of `jasmine.createSpyObj` with automatic discovery of functions and property getters given a Class, without requiring an instance of an object.\n\nIf you'd want to spy on a property without a getter, then you can simply pass in the property name like `autoSpyObj(WeatherService, ['currentWeather$'])`.\n\nReturn value of `autoSpyObj` will be a true mock of the Class with spy-able methods and properties, making it easy to control and modify the return values of external dependencies during testing.\n\nIf property name ends with `$` indicating that the property is an Observable, then you can specify an optional `ObservablePropertyStrategy` to prefer `{}`, `new Observable()` or `new BehaviorSubject(null)` default values for your mocked properties.\n\nUsage\n\n```ts\nconst weatherServiceSpy = autoSpyObj(WeatherService)\n```\n\nAlternate Usage\n\n```ts\nconst weatherServiceSpy = autoSpyObj(\n  WeatherService,\n  ['currentWeather$'],\n  ObservablePropertyStrategy.BehaviorSubject\n)\n```\n\n`autoSpyObj` replaces the more verbose and difficult to maintain code, shown below:\n\n```ts\njasmine.createSpyObj(WeatherService.name, [\n  'getCurrentWeather',\n  'getCurrentWeatherByCoords',\n  'updateCurrentWeather',\n])\naddPropertyAsBehaviorSubject(weatherServiceSpy, 'currentWeather$')\n```\n\n### `addProperty(object: object, propertyName: string, valueToReturn: object)`\n\nWhen creating a mock object, add a property to that object with a property getter, so you can use a jasmine.spyOnProperty.\n\nUsage\n\n```ts\n  weatherServiceMock = jasmine.createSpyObj('WeatherService', ['getCurrentWeather'])\n  addPropertyAsBehaviorSubject(weatherServiceMock, 'currentWeather', null)\n  ...\n  spyOnProperty(weatherServiceMock, 'currentWeather$').and.returnValue({ temp = 72})\n```\n\n### `addPropertyAsBehaviorSubject(object: object, propertyName: string)`\n\nConvenience method to configure a property as a BehaviorSubject, so you can update its value before each test by calling .next on it.\n\nUsage\n\n```ts\n  weatherServiceMock = jasmine.createSpyObj('WeatherService', ['getCurrentWeather'])\n  addPropertyAsBehaviorSubject(weatherServiceMock, 'currentWeather$')\n  ...\n  weatherServiceMock.currentWeather$.next(fakeWeather)\n```\n\n### _deprecated_ `createComponentMock(className: string, selectorName?: string, template = '')`\n\n_Deprecated_ Use `ng-mocks` instead. https://ng-mocks.sudo.eu/api/MockComponent.\n\n1. Install using `install i -D ng-mocks`\n2. Refactor `createComponentMock` function calls to look like the sample below:\n\n```TypeScript\nTestBed.configureTestingModule({\n  declarations: [\n    // for a single component\n    MockComponent(Component),\n\n    // for a set of components\n    ...MockComponents(Component1, Component2),\n  ],\n})\n```\n\nCreates a mock class decorated with @Component, if not specified selector is inferred to be MyClassComponent -\u003e app. Provides an option to override empty template.\n\nUsage\n\n```ts\nTestBed.configureTestingModule({\n      declarations: [ ..., createComponentMock('CurrentWeatherComponent')]\n      ...\n})\n```\n\nNote: Inferred selector in the above example is 'app-current-weather'.\n\nReplaces boilerplate\n\n```ts\n@Component({\n  selector: 'app-current-weather',\n  template: '',\n})\nclass MockCurrentWeatherComponent {}\n```\n\n### `getNativeElementByTestId\u003cTComponent\u003e(fixture: ComponentFixture\u003cTComponent\u003e, testId: string = '')`\n\nHelper function to retrieve the native element associated with a specific `data-testid`` within a component fixture.\n\nUsage\n\n```html\n\u003cspan class=\"left-pad\" data-testid=\"title\"\u003eLemonMart\u003c/span\u003e\n```\n\n```ts\nit('should render title', () =\u003e {\n  const fixture = TestBed.createComponent(AppComponent)\n  fixture.detectChanges()\n  const titleElement = getNativeElementByTestId(fixture, 'title')\n  expect(titleElement.textContent).toContain('LemonMart')\n})\n```\n\n### `injectClass\u003cTDependency\u003e(dependency: Type\u003cTDependency\u003e | AbstractType\u003cTDependency\u003e): TDependency`\n\nHelper function to inject a dependency, like a service, into the TestBed with a typed return variable.\n\nUsage\n\n```ts\nbeforeEach(() =\u003e {\n  weatherService = injectClass(WeatherService)\n})\n```\n\nReplaces\n\n```ts\nbeforeEach(() =\u003e {\n  weatherService = TestBed.inject(WeatherService)\n})\n```\n\n### `injectSpy\u003cTDependency\u003e(dependency: Type\u003cTDependency\u003e | AbstractType\u003cTDependency\u003e): jasmine.SpyObj\u003cTDependency\u003e`\n\nSimilar to `injectClass`, but more descriptive to read for developers if returning a mocked SpyObj.\n\nUsage\n\n```ts\nbeforeEach(() =\u003e {\n  weatherServiceMock = injectSpy(WeatherService)\n})\n```\n\nReplaces\n\n```ts\nbeforeEach(() =\u003e {\n  weatherServiceMock = TestBed.inject(WeatherService) as any\n})\n```\n\n### `getAllFunctions(prototype: any, props?: (string | number | symbol)[])`\n\nHelper function that return all functions in a given Class using reflection, so you don't have to provide an instance of the object.\n\n### `getAllProperties(prototype: any, props?: (string | number | symbol)[])`\n\nHelper function that return all property getters in a given Class using reflection, so you don't have to provide an instance of the object.\n\n## Contributing\n\n- Send PR, will accept\n- To setup the project, run `npm install`\n- Test against the example project listed below using `npm pack` to create a `.tgz` file and install the `.tgz` file using `npm install -D ../path/to/your.tgz`\n  - Using `npm link` doesn't work as expected due `devDependencies` being symlinked to the parent Angular project, causing issues with the framework.\n- To publish the project, run `npm version major|minor|patch`\n  \u003e Read more about that setup by Isaac Schlueter [here](https://blog.npmjs.org/post/184553141742/easy-automatic-npm-publishes)\n","funding_links":[],"categories":["Testing"],"sub_categories":["Component"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fduluca%2Fangular-unit-test-helper","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fduluca%2Fangular-unit-test-helper","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fduluca%2Fangular-unit-test-helper/lists"}