@ -50,6 +50,8 @@ After signing into a tenant, a tenant switcher appears in the user menu — clic
Users can also leave a tenant. Leaving doesn't delete the association record — it marks it as inactive. This preserves foreign key relationships with other entities. If the user is invited back later, the association is simply reactivated instead of recreated.
The same soft removal is available to a tenant admin from the user list — a **Remove from tenant** action that takes a user off the tenant without touching the global account. Useful for the obvious case: an employee leaves the company, the admin removes them from the tenant, but their account (and any other tenant they belong to) stays intact.
Back to our earlier scenario: the financial consultant now has one account, one password. She picks which company to work in at login, switches between them during the day. The system knows it's the same person, and the audit log can trace her actions across every tenant.
The configuration above resolves the current tenant from the incoming request (inbound). To make the **outbound** URLs your application generates — such as the password reset link inside an Account email — point to the tenant's subdomain as well, configure `AppUrlOptions`. See [Application URLs](../../infrastructure/app-urls.md#multi-tenant-aware-urls).
##### Custom Tenant Resolvers
You can add implement your custom tenant resolver and configure the `AbpTenantResolveOptions` in your module's `ConfigureServices` method as like below:
"Description": "Configure cross-application URLs in ABP with AppUrlOptions and IAppUrlProvider, including multi-tenant subdomain templates and redirect URL validation."
}
```
# Application URLs
ABP provides the `AppUrlOptions` options class and the `IAppUrlProvider` service to centrally configure and resolve URLs that point to **other applications** in your solution (for example, an MVC/Razor Pages UI, an Auth Server, an HTTP API host, etc.). They are typically used when code in one application needs to build a link that targets another — like the Account module putting a **password reset link** into an email.
* Defines `AppUrlOptions` to register the **root URL** and named relative URLs of each application.
* Provides `IAppUrlProvider` to **resolve** those URLs at runtime, with optional **tenant-aware** placeholder substitution.
* Supports **subdomain-style templates** (e.g. `https://{0}.example.com`) that produce per-tenant URLs without extra code.
* Maintains a `RedirectAllowedUrls` list used by `IAppUrlProvider.IsRedirectAllowedUrlAsync` to validate redirect targets.
> `AppUrlOptions` is defined in the `Volo.Abp.UI.Navigation` package, which comes pre-installed with the [application startup template](../../solution-templates/layered-web-application).
## Configuring Application URLs
`AppUrlOptions` exposes a dictionary of **applications**, each with a `RootUrl` and a set of named `Urls`.
**Example: Set the root URL and a named URL for the MVC application**
* `"MVC"` is the **application key**. Some modules (such as Account) register their URLs under a known key — `"MVC"` is the default for the **server-side UI**. You can use any key you want for your own applications.
* `RootUrl` is the **base URL** of that application.
* `Urls[urlName]` is a **relative path** appended to `RootUrl`. The final URL is built as `RootUrl.EnsureEndsWith('/') + Urls[urlName]`, so the relative path should **not** start with a `/`. When `RootUrl` is `null`, the value of `Urls[urlName]` is returned as-is.
The Account module, for example, **pre-registers** its URLs in its application module:
**Example: How the Account module registers the password reset URL**
> So configuring `Applications["MVC"].RootUrl` in your own module is usually enough to make password reset and similar Account email links point to the right host.
### Defaults in the application startup template
The ABP **application startup template** wires `Applications["MVC"].RootUrl` to the `App:SelfUrl` setting and seeds `RedirectAllowedUrls` from `App:RedirectAllowedUrls`:
> This is why Account email links point to your **host URL** out of the box: they reuse `App:SelfUrl`. If that default isn't what you want — for example, in a subdomain-based **multi-tenant** setup — override `Applications["MVC"].RootUrl` with the template you need (see [Multi-Tenant Aware URLs](#multi-tenant-aware-urls)).
## Using `IAppUrlProvider`
[Inject](../fundamentals/dependency-injection.md) the `IAppUrlProvider` service into any class that needs to build a cross-application URL.
**Example: Resolve a root URL and a named URL of the MVC application**
```csharp
public class MyNotificationSender : ITransientDependency
{
private readonly IAppUrlProvider _appUrlProvider;
public MyNotificationSender(IAppUrlProvider appUrlProvider)
{
_appUrlProvider = appUrlProvider;
}
public async Task SendAsync()
{
var rootUrl = await _appUrlProvider.GetUrlAsync("MVC");
var pageUrl = await _appUrlProvider.GetUrlAsync("MVC", "MyPage");
}
}
```
* `GetUrlAsync(appName)` returns the configured `RootUrl` for the given application.
* `GetUrlAsync(appName, urlName)` returns the **combined URL** described above.
* `GetUrlAsync(...)` throws an `AbpException` when the resolved URL is `null` or empty (e.g. both `RootUrl` and `Urls[urlName]` are unset). Use `GetUrlOrNullAsync(...)` if you'd rather get `null` and decide what to do yourself.
* `NormalizeUrlAsync(url)` applies tenant placeholder substitution to a URL string that you already have. Useful when the URL doesn't come from `AppUrlOptions`.
## Multi-Tenant Aware URLs
If your solution uses **subdomain-based** multi-tenancy (see the [Domain/Subdomain Tenant Resolver](../architecture/multi-tenancy/index.md#domainsubdomain-tenant-resolver)), you'll usually want the **outbound URLs** you generate (email links, redirects) to also be tenant-aware — otherwise the link in a password reset email won't point to the tenant's subdomain.
`AppUrlOptions` supports the following **placeholders** in any URL value. They are substituted by `IAppUrlProvider` based on the **current tenant**:
| Placeholder | Replaced with |
| --- | --- |
| `{0}` | Current tenant **name** |
| `{%{{{ {{tenantName}} }}}%}` | Current tenant **name** |
| `{%{{{ {{tenantId}} }}}%}` | Current tenant **id** |
The `{0}` placeholder uses the **same convention** as `AddDomainTenantResolver("{0}.example.com")`, so a typical subdomain-tenant setup looks like this:
**Example: Tenant-aware Account email links via a subdomain template**
With this configuration, password reset emails sent to a tenant whose name is `acme` will contain a link starting with `https://acme.example.com/`, matching the tenant's subdomain.
### Host (no tenant) Fallback
When there is **no current tenant** (host-side request), the placeholder **and the dot following it** are removed together:
A single subdomain-style template like the ones above therefore works for **both** tenant and host scenarios without extra configuration.
> If your subdomain is based on the tenant **id** rather than the name, use `https://{%{{{ {{tenantId}} }}}%}.example.com`. The resolver's `{0}` placeholder accepts both name and id when finding a tenant, but `AppUrlOptions` substitutes `{0}` with the tenant **name**; if those two don't match, switch to the explicit `{%{{{ {{tenantId}} }}}%}` form on the `AppUrlOptions` side.
## Redirect Allowed URLs
`AppUrlOptions.RedirectAllowedUrls` is a list of URL entries used by `IAppUrlProvider.IsRedirectAllowedUrlAsync(url)` to decide whether a redirect target is allowed. A URL is allowed when it satisfies **either** of:
* **Prefix match**: the URL string **starts with** a configured entry (case-insensitive).
* **Subdomain match**: the URL and the entry have the **same scheme** and **port**, and the URL's host **ends with**`.{entry-host}`.
**Example: Register allowed redirect URLs (including a wildcard)**
* A **plain entry** like `https://my-app.com` allows any URL that starts with that prefix, plus any subdomain of `my-app.com`.
* A **wildcard entry** like `https://*.my-app.com` allows any subdomain of `my-app.com`; the `*.` is stripped before the subdomain check.
* Entries also go through **tenant placeholder substitution**, so `https://{0}.my-app.com` is resolved to the current tenant's URL first (e.g. `https://acme.my-app.com`) and then compared. Use the wildcard form when you need to allow *any* tenant subdomain regardless of the current tenant.
BLOB Storing Aws Provider can store BLOBs in [Amazon Simple Storage Service](https://aws.amazon.com/s3/).
BLOB Storing Aws Provider can store BLOBs in [Amazon Simple Storage Service](https://aws.amazon.com/s3/) and **S3-compatible storage services** like MinIO, DigitalOcean Spaces, Cloudflare R2, and others.
> Read the [BLOB Storing document](../blob-storing) to understand how to use the BLOB storing system. This document only covers how to configure containers to use a Aws BLOB as the storage provider.
* **UseTemporaryFederatedCredentials** (bool): Use [federated user temporary credentials](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationToken.html) to access AWS services, default : `false`.
* **ProfileName** (string): The [name of the profile](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html) to get credentials from.
* **ProfilesLocation** (string): The path to the aws credentials file to look at.
* **Region** (string): The system name of the service.
* **Region** (string): The system name of the AWS region (e.g., `us-east-1`). **Required** for real AWS S3. Optional when `ServiceURL` is configured for an S3-compatible service; some services accept any value (or `auto` for Cloudflare R2).
* **ServiceURL** (string): Custom service URL for S3-compatible APIs (e.g., MinIO, DigitalOcean Spaces, Cloudflare R2). If not specified, the default AWS S3 service URL will be used based on the region. When using S3-compatible services, this should point to your service endpoint (e.g., `https://minio.example.com:9000`). The AWS SDK automatically appends a trailing slash to the configured value.
* **DisablePayloadSigning** (bool): Default `false`. When set to `true`, the provider sends `x-amz-content-sha256: UNSIGNED-PAYLOAD` on `PutObject` requests instead of the streaming chunked signature (`STREAMING-AWS4-HMAC-SHA256-PAYLOAD`) that the AWS SDK v4 uses by default. Required for Cloudflare R2 and other S3-compatible services that do not implement streaming signing. The endpoint must be HTTPS when this option is enabled. Leave as `false` for real AWS S3.
* **Policy** (string): An IAM policy in JSON format that you want to use as an inline session policy.
* **DurationSeconds** (int): Validity period(s) of a temporary access certificate,minimum is 900 and the maximum is 3600. **note**: Using sub-accounts operated OSS,if the value is 0.
* **ContainerName** (string): You can specify the container name in Aws. If this is not specified, it uses the name of the BLOB container defined with the `BlobContainerName` attribute (see the [BLOB storing document](../blob-storing)). Please note that Aws has some **rules for naming containers**. A container name must be a valid DNS name, conforming to the [following naming rules](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html):
* Buckets used with Amazon S3 Transfer Acceleration can't have dots (.) in their names. For more information about transfer acceleration, see Amazon S3 Transfer Acceleration.
* **CreateContainerIfNotExists** (bool): Default value is `false`, If a container does not exist in Aws, `AwsBlobProvider` will try to create it.
## S3-Compatible Services
The AWS provider supports S3-compatible storage services by configuring the `ServiceURL` property. Here are some examples:
aws.Region = "auto"; // Cloudflare R2 uses 'auto' as region
aws.DisablePayloadSigning = true; // R2 does not implement streaming chunked payload signing
aws.ContainerName = "my-bucket";
aws.CreateContainerIfNotExists = true;
});
});
});
````
> **Note**: When using S3-compatible services, the provider automatically enables path-style requests which are required by most S3-compatible implementations.
> **Note on `DisablePayloadSigning`**: AWS SDK v4 sends `PutObject` requests with `x-amz-content-sha256: STREAMING-AWS4-HMAC-SHA256-PAYLOAD`. Cloudflare R2 (and some other S3-compatible services) return `501 NotImplemented` for this signing mode. Setting `DisablePayloadSigning = true` switches to `UNSIGNED-PAYLOAD`, which these services accept. The endpoint must be HTTPS. Leave it `false` for real AWS S3.
## Aws Blob Name Calculator
Aws Blob Provider organizes BLOB name and implements some conventions. The full name of a BLOB is determined by the following rules by default:
@ -36,6 +36,20 @@ More providers will be implemented by the time. You can [request](https://github
Multiple providers **can be used together** by the help of the **container system**, where each container can uses a different provider.
### S3 Compatibility
The [AWS provider](./aws.md) supports not only Amazon S3 but also **S3-compatible APIs** from various cloud providers and self-hosted solutions. This means you can use the same AWS provider to connect to:
* **Any other S3-compatible storage** - Including private cloud solutions
To use S3-compatible services, configure the `ServiceURL` property in the AWS provider configuration to point to your S3-compatible endpoint. Some services (e.g., Cloudflare R2) also require `DisablePayloadSigning = true` because they do not implement the streaming chunked payload signing that AWS SDK v4 uses by default. See the [AWS provider document](aws.md) for full configuration examples.
> BLOB storing system can not work unless you **configure a storage provider**. Refer to the linked documents for the storage provider configurations.
@ -15,6 +15,8 @@ Entity prop extension system allows you to add a new column to the data table fo
You will have access to the current entity in your code and display its value, make the column sortable, perform visibility checks, and more. You can also render custom HTML in table cells.
> **Standalone-first:** Current ABP templates use standalone APIs. The `loadChildren` examples below lazy-load routes from `createRoutes({ ... })` — they do not require NgModules. Legacy NgModule projects can pass the same options to `IdentityModule.forLazy({ ... })` instead. See [ABP Now Supports Angular Standalone Applications](https://abp.io/community/articles/abp-now-supports-angular-standalone-applications-zzi2rr2z).
## How to Set Up
In this example, we will add a "Name" column and display the value of the `name` field in the user management page of the [Identity Module](../../../modules/identity.md).
@ -64,7 +66,7 @@ Import `identityEntityPropContributors` in your routing configuration and pass i
```js
// src/app/app.routes.ts
// other imports
import { Routes } from '@angular/router';
import { identityEntityPropContributors } from './entity-prop-contributors';
That is it, `nameProp` entity prop will be added, and you will see the "Name" column next to the usernames on the grid in the users page (`UsersComponent`) of the `identity` package.
@ -16,6 +16,8 @@ Form prop extension system allows you to add a new field to the create and/or ed
You can validate the field, perform visibility checks, and do more. You will also have access to the current entity when creating a contributor for an edit form.
> **Standalone-first:** Current ABP templates use standalone APIs. The `loadChildren` examples below lazy-load routes from `createRoutes({ ... })` — they do not require NgModules. Legacy NgModule projects can pass the same options to `IdentityModule.forLazy({ ... })` instead. See [ABP Now Supports Angular Standalone Applications](https://abp.io/community/articles/abp-now-supports-angular-standalone-applications-zzi2rr2z).
## How to Set Up
In this example, we will add a "Date of Birth" field in the user management page of the [Identity Module](../../../modules/identity.md) and validate it.
@ -69,7 +71,7 @@ Import `identityCreateFormPropContributors` and `identityEditFormPropContributor
That is it, `birthdayProp` form prop will be added, and you will see the datepicker for the "Date of Birth" field right before the "Email address" in the forms of the users page in the `identity` package.
@ -15,6 +15,8 @@ Entity action extension system allows you to add a new action to the action menu
You can take any action (open a modal, make an HTTP API call, redirect to another page... etc) by writing your custom code. You can also access the current entity in your code.
> **Standalone-first:** Current ABP templates use standalone APIs. The `loadChildren` examples below lazy-load routes from `createRoutes({ ... })` — they do not require NgModules. Legacy NgModule projects can pass the same options to `IdentityModule.forLazy({ ... })` instead. See [ABP Now Supports Angular Standalone Applications](https://abp.io/community/articles/abp-now-supports-angular-standalone-applications-zzi2rr2z).
## How to Set Up
In this example, we will add a "Click Me!" action and alert the current row's `userName` in the user management page of the [Identity Module](../../../modules/identity.md).
@ -56,12 +58,12 @@ The list of actions, conveniently named as `actionList`, is a **doubly linked li
### Step 2. Import and Use Entity Action Contributors
Import `identityEntityActionContributors` in your routing configuration and pass it to the static `configureRoutes` method for `identity` routes as seen below:
Import `identityEntityActionContributors` in your routing configuration and pass it to the static `createRoutes` method for `identity` routes as seen below:
```js
// src/app/app.routes.ts
// other imports
import { Routes } from '@angular/router';
import { identityEntityActionContributors } from './entity-action-contributors';
That is it, `alertUserName` entity action will be added as the last action on the grid dropdown in the "Users" page (`UsersComponent`) of the `identity` package.
## How to Place a Custom Modal and Trigger It by Entity Actions
* [Dynamic Form (or Form Prop) Extensions](dynamic-form-extensions.md)
> **Standalone-first:** Current ABP templates use standalone APIs (`app.config.ts`, `app.routes.ts`, and `createRoutes()`). Extension examples register contributors through route-level lazy loading — `loadChildren` returns routes from `createRoutes({ ... })`, not NgModules. Legacy NgModule projects can pass the same contributor options to `SomeModule.forLazy({ ... })` instead. See [ABP Now Supports Angular Standalone Applications](https://abp.io/community/articles/abp-now-supports-angular-standalone-applications-zzi2rr2z) for the `forLazy()` → `createRoutes()` migration.
## Extensible Table Component
Using [ngx-datatable](https://github.com/swimlane/ngx-datatable) in extensible table.
ABP has an ever-growing number of feature modules and [introducing a new one](../../architecture/modularity/basics.md) is always possible. When the UI is Angular, these features have modular Angular libraries accompanying them.
> **Standalone-first:** Current templates use standalone APIs. Configuration providers such as `provideIdentityConfig()` belong in `app.config.ts`, and features are lazy-loaded via `createRoutes()` in `app.routes.ts`. The `loadChildren` pattern below loads **route definitions**, not NgModules. In legacy NgModule projects, replace `createRoutes()` with `IdentityModule.forLazy()` (or the equivalent `forLazy()` method on the feature module). See [ABP Now Supports Angular Standalone Applications](https://abp.io/community/articles/abp-now-supports-angular-standalone-applications-zzi2rr2z).
## Feature Library Content
Each library has at least two key elements:
@ -85,6 +87,20 @@ When you load the identity feature like this, the "Users" page, for example, wil
Depending on the library, the `.createRoutes` static method may also receive some options that configure how the feature works.
#### Legacy NgModule projects
If your application still uses NgModules, lazy-load the feature with `forLazy()` instead:
Pass the same options object to `forLazy({ ... })` that you would pass to `createRoutes({ ... })` when configuring extensions or other feature options.
---
<supid="f-modify-route"><b>1</b></sup>_Libraries expect to work at a predefined path. Please check [how to patch a navigation element](./modifying-the-menu.md#how-to-patch-or-remove-a-navigation-element), if you want to use a different path from the default one (e.g. '/identity')._<sup>[↩](#a-modify-route)</sup>
You can get the value of a feature on the client-side using the [config state service](./config-state.md) if it is allowed by the feature definition on the server-side.
You can get the value of a feature on the client-side using the [config state service](./config-state-service.md) if it is allowed by the feature definition on the server-side.
> This document explains how to get feature values in an Angular application. See the [Features document](../../infrastructure/features.md) to learn the feature system.
Additional UI extensibility points ([Entity action extensions](../angular/entity-action-extensions.md), [data table column extensions](../angular/data-table-column-extensions.md), [page toolbar extensions](../angular/page-toolbar-extensions.md) and others) are used in ABP pages to allow to control entity actions, table columns and page toolbar of a page. If you replace a page, you need to apply some configurations to be able to work extension components in your component. Let's see how to do this by replacing the roles page.
> **Standalone-first:** The example below uses standalone components with an `imports` array and `inject()`. Current ABP templates follow this pattern. Module-based examples in older docs remain valid for legacy projects — see [ABP Now Supports Angular Standalone Applications](https://abp.io/community/articles/abp-now-supports-angular-standalone-applications-zzi2rr2z).
The authentication functionality has been moved from @abp/ng.core to @abp/ng.ouath since v7.0.
The authentication functionality has been moved from @abp/ng.core to @abp/ng.oauth since v7.0.
If your app is version 8.3 or higher, you should include "provideAbpOAuth()" after "provideAbpCore()" in the `appConfig` array of your `app.config.ts`.
@ -15,6 +15,8 @@ Page toolbar extension system allows you to add a new action to the toolbar of a
You can take any action (open a modal, make an HTTP API call, redirect to another page... etc) by writing your custom code. You can also access to page data (the main record, usually an entity list) in your code. Additionally, you can pass in custom components instead of using the default button.
> **Standalone-first:** Current ABP templates use standalone APIs. The `loadChildren` examples below lazy-load routes from `createRoutes({ ... })` — they do not require NgModules. Legacy NgModule projects can pass the same options to `IdentityModule.forLazy({ ... })` instead. See [ABP Now Supports Angular Standalone Applications](https://abp.io/community/articles/abp-now-supports-angular-standalone-applications-zzi2rr2z).
## How to Add an Action to Page Toolbar
In this example, we will add a "Click Me!" action and log `userName` of all users in the user management page of the [Identity Module](../../../modules/identity.md) to the console.
@ -65,7 +67,7 @@ Import `identityToolbarActionContributors` in your routing configuration and pas
```js
// src/app/app.routes.ts
// other imports
import { Routes } from '@angular/router';
import { identityToolbarActionContributors } from './toolbar-action-contributors';
That is it, `logUserNames` toolbar action will be added as the first action on the page toolbar in the users page (`UsersComponent`) of the `identity` package.
## How to Add a Custom Component to Page Toolbar
@ -100,7 +116,7 @@ We need to have a component before we can pass it to the toolbar action contribu
```js
// src/app/click-me-button.component.ts
import { Component, Inject } from '@angular/core';
import { Component, inject } from '@angular/core';
import { IdentityUserDto } from '@abp/ng.identity/proxy';
import { ActionData, EXTENSIONS_ACTION_DATA } from '@abp/ng.components/extensible';
That is it, `logUserNames` toolbar action will be added as the first action on the page toolbar in the users page (`UsersComponent`) of the `identity` package and it will be triggered by a custom button, i.e. `ClickMeButtonComponent`. Please note that **component projection is not limited to buttons** and you may use other UI components.
## How to Place a Custom Modal and Trigger It by Toolbar Actions
@ -167,7 +166,7 @@ When you run the development server, variables defined in _environment.ts_ take
2. Run `yarn` or `npm install` if you have not installed dependencies already.
3. Run `yarn build:prod` or `npm run build:prod`.
<imgalt="Angular compiler optimizing the build using Terser"src="./images/quick-start---self-signed-certificate-error.png"width="400px"style="max-width:100%">
<imgalt="Browser blocking access to backend API due to self-signed certificate error"src="./images/quick-start---self-signed-certificate-error.png"width="400px"style="max-width:100%">
Depending on project size, the compilation may take a few minutes. When it is finished, the compiled output will be placed inside the _/dist_ folder. Voila! You have deployment-ready build artifacts.
You can get settings on the client-side using the [config state service](./config-state.md) if they are allowed by their setting definition on the server-side.
You can get settings on the client-side using the [config state service](./config-state-service.md) if they are allowed by their setting definition on the server-side.
> This document only explains how settings work in the Angular UI projects. See the [settings document](../../infrastructure/settings.md) to understand the ABP setting system.
"Description": "Learn how to unit test your ABP Angular UI applications with preconfigured Karma and Jasmine, plus ABP-specific testing topics."
"Description": "Learn how to unit test your ABP Angular UI applications with preconfigured Vitest and TestBed, plus ABP-specific testing topics."
}
```
@ -9,89 +9,105 @@
ABP Angular UI is tested like any other Angular application. So, [the guide here](https://angular.dev/guide/testing) applies to ABP too. That said, we would like to point out some **unit testing topics specific to ABP Angular applications**.
## Setup
## Test Stack
In Angular, unit tests use [Karma](https://karma-runner.github.io/) and [Jasmine](https://jasmine.github.io) by default. Although we like Jest more, we chose not to deviate from these defaults, so **the application template you download will have Karma and Jasmine preconfigured**. You can find the Karma configuration inside the _karma.conf.js_ file in the root folder. You don't have to do anything. Adding a spec file and running `npm test` will work.
The application template you download is preconfigured for unit testing. You can add a `*.spec.ts` file and run `yarn test` without adding extra test infrastructure.
## Basics
| Package / API | Purpose |
| --- | --- |
| [Vitest](https://vitest.dev/) | Test runner and assertion library. |
| [jsdom](https://github.com/jsdom/jsdom) | Browser-like DOM environment for component tests. |
| `@angular/core/testing` (`TestBed`) | The standard testing utilities of Angular for components, services, and pipes. |
| `@abp/ng.core/testing` | ABP testing module and helpers that replace real ABP services with mocks. |
| `@abp/ng.theme.shared/testing` | Testing module for shared theme features such as validation. |
An over-simplified spec file looks like this:
ABP Angular packages in the [framework repository](https://github.com/abpframework/abp/tree/dev/npm/ng-packs) use the same Vitest setup. Library tests there also use [`@ngneat/spectator/vitest`](https://github.com/ngneat/spectator) for HTTP and component tests, but the application template uses `TestBed` directly.
```js
import { CoreTestingModule } from "@abp/ng.core/testing";
import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing";
import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing";
import { ComponentFixture, TestBed, waitForAsync } from "@angular/core/testing";
import { NgxValidateCoreModule } from "@ngx-validate/core";
import { MyComponent } from "./my.component";
## Configuration
describe("MyComponent", () => {
let fixture: ComponentFixture<MyComponent>;
The test target in _angular.json_ uses Angular's built-in Vitest builder:
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [
CoreTestingModule.withConfig(),
ThemeSharedTestingModule.withConfig(),
ThemeBasicTestingModule.withConfig(),
NgxValidateCoreModule,
],
providers: [
/* mock providers here */
],
}).compileComponents();
})
);
```json
// angular.json
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
});
"test": {
"builder": "@angular/build:unit-test"
}
```
it("should be initiated", () => {
expect(fixture.componentInstance).toBeTruthy();
});
});
Spec files are compiled with _tsconfig.spec.json_, which enables Vitest globals:
```json
// tsconfig.spec.json
{
"compilerOptions": {
"types": ["vitest/globals"]
},
"include": ["src/**/*.spec.ts"]
}
```
If you take a look at the imports, you will notice that we have prepared some testing modules to replace built-in ABP modules. This is necessary for providing mocks for some features which otherwise would break your tests. Please remember to **use testing modules** and **call their `withConfig` static method**.
You do not need a _karma.conf.js_ file. Angular CLI wires Vitest and jsdom for you.
## Tips
## Running Tests
### Angular Testing Library
Run tests in watch mode:
```bash
yarn test
```
Although you can test your code with Angular TestBed, you may find [Angular Testing Library](https://testing-library.com/docs/angular-testing-library/intro) a good alternative.
Run tests once, which is useful for CI:
The simple example above can be written with Angular Testing Library as follows:
```bash
ng test --watch=false
```
Vitest exits with a non-zero status code when a test fails, so the command above works in pipelines.
## Basics
```js
An over-simplified spec file looks like this:
```ts
import { CoreTestingModule } from "@abp/ng.core/testing";
import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing";
import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing";
import { ComponentFixture } from "@angular/core/testing";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { NgxValidateCoreModule } from "@ngx-validate/core";
import { render } from "@testing-library/angular";
import { AuthService } from "@abp/ng.core";
import { vi } from "vitest";
import { MyComponent } from "./my.component";
describe("MyComponent", () => {
let fixture: ComponentFixture<MyComponent>;
let mockAuthService: { isAuthenticated: boolean; navigateToLogin: ReturnType<typeofvi.fn> };
Very similar, as you can see. The real difference kicks in when we use queries and fire events.
If you take a look at the imports, you will notice that we have prepared some testing modules to replace built-in ABP modules. This is necessary for providing mocks for some features which otherwise would break your tests. Please remember to **use testing modules** and **call their `withConfig` static method**.
```js
// other imports
import { getByLabelText, screen } from "@testing-library/angular";
import userEvent from "@testing-library/user-event";
Current templates use standalone components, so put the component under test in the `imports` array instead of `declarations`.
describe("MyComponent", () => {
beforeEach(/* removed for sake of brevity */);
If your application uses `@abp/ng.theme.basic`, also import `ThemeBasicTestingModule.withConfig()` from `@abp/ng.theme.basic/testing`.
The **queries in Angular Testing Library follow practices for maintainable tests**, the user event package provides a **human-like interaction** with the DOM, and the library in general has **a clear API** that simplifies component testing. Please find some useful links below:
The template's `home.component.spec.ts` is a good reference for mocking ABP services and asserting DOM behavior with `TestBed`.
One thing to remember is that Karma runs tests in real browser instances. That means, you will be able to see the result of your test code, but also have problems with components attached to the document body which may not get cleared after each test, even when you configure Karma to do so.
Tests run in jsdom, not a real browser. Components attached to `document.body` — such as modals, confirmation dialogs, and toasts — may not be removed automatically between specs.
We have prepared a simple function with which you can clear any leftover DOM elements after each test.
We have prepared a simple function with which you can clear leftover DOM elements after each test:
Please make sure you use it because Karma will fail to remove dialogs otherwise and you will have multiple copies of modals, confirmation boxes, and alike.
Please use it when you test features that render into the document body. Otherwise you may end up with multiple copies of modals, confirmation boxes, and similar elements.
### Waiting
Some components, modals, in particular, work off-detection-cycle. In other words, you cannot reach DOM elements inserted by these components immediately after opening them. Similarly, inserted elements are not immediately destroyed upon closing them.
Some components, modals in particular, work off the change-detection cycle. In other words, you cannot reach DOM elements inserted by these components immediately after opening them. Similarly, inserted elements are not immediately destroyed upon closing them.
For this purpose, we have prepared a `wait` function.
For this purpose, we have prepared a `wait` function:
The `wait` function takes a second parameter, i.e. timeout (default: `0`). Try not to use it though. Using a timeout bigger than `0` is usually a signal that something is not quite right.
## Testing Example
### Angular Testing Library
Although you can test your code with Angular TestBed, you may find [Angular Testing Library](https://testing-library.com/docs/angular-testing-library/intro) a good alternative. It is not included in the application template by default, but you can add `@testing-library/angular` and `@testing-library/user-event` if you prefer that style.
Here is an example test suite. It doesn't cover all, but gives quite a good idea about what the testing experience will be like.
The ABP testing modules work the same way with Testing Library:
```js
import { clearPage, CoreTestingModule, wait } from "@abp/ng.core/testing";
import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing";
```ts
import { CoreTestingModule } from "@abp/ng.core/testing";
import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing";
import { ComponentFixture } from "@angular/core/testing";
import {
NgbCollapseModule,
NgbDatepickerModule,
NgbDropdownModule,
} from "@ng-bootstrap/ng-bootstrap";
import { NgxValidateCoreModule } from "@ngx-validate/core";
import { CountryService } from "@proxy/countries";
import {
findByText,
getByLabelText,
getByRole,
getByText,
queryByRole,
render,
screen,
} from "@testing-library/angular";
import userEvent from "@testing-library/user-event";
import { BehaviorSubject, of } from "rxjs";
import { CountryComponent } from "./country.component";
const list$ = new BehaviorSubject({
items: [{ id: "ID_US", name: "United States of America" }],
totalCount: 1,
});
describe("Country", () => {
let fixture: ComponentFixture<CountryComponent>;
import { render, screen } from "@testing-library/angular";
The **queries in Angular Testing Library follow practices for maintainable tests**, the user event package provides a **human-like interaction** with the DOM, and the library in general has **a clear API** that simplifies component testing. Please find some useful links below:
const name = getByText(table, "United States of America");
Here is an example based on the application template's `home.component.spec.ts`. It shows how to mock an ABP service and assert component state and DOM output:
For list pages with modals, confirmations, and service proxies, keep using the ABP testing modules, mock your generated proxy services with `vi.fn()`, and use `clearPage` / `wait` when body-level UI is involved.
You would need a different configuration for your CI environment. To set up a new configuration for your unit tests, find the test project in _angular.json_ file and add one as seen below:
If you need a dedicated CI configuration, add one under the `test` target in _angular.json_:
```json
// angular.json
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": { /* several options here */ },
"builder": "@angular/build:unit-test",
"configurations": {
"production": {
"karmaConfig": "karma.conf.prod.js"
"ci": {
"watch": false
}
}
}
```
Now you can copy the _karma.conf.js_ as _karma.conf.prod.js_ and use any configuration you like in it. Please check [Karma configuration file document](http://karma-runner.github.io/5.2/config/configuration-file.html) for config options.
Finally, don't forget to run your CI tests with the following command:
@ -68,6 +68,8 @@ This configuration will allow subdomain tenant resolving. Ex, if you have a tena
**For angular application**, you don't need to add anything since we will be overriding the angular environment via kubernetes values file.
> The configuration above resolves the current tenant from the incoming request. To make outbound URLs generated through `IAppUrlProvider` (Account email links, redirects, etc.) also tenant-aware, configure `AppUrlOptions` with the same `{0}` template. See [Application URLs](../framework/infrastructure/app-urls.md#multi-tenant-aware-urls).
## Configuring AuthServer
When the tenant try to login from an application (Ex `https://volosoft.angular.mystore.dev`) it will be redirected to AuthServer (`https://volosoft.authserver.mystore.dev`) and you will be seeing a **HTTP 400 error** related to `invalid redirect_uri`. If you check the authserver application logs (under Logs/logs.txt file or console logs), you will notice that the `https://volosoft.angular.mystore.dev` is not a valid redirect_uri since it is not been seeded by the OpenIddictDataSeeder. Only the **host** applications, gateways and microservice URLs are seeded (like `https://angular.mystore.dev`).
> The host part of the password reset link is built from `AppUrlOptions.Applications["MVC"].RootUrl`. Configure it if the default `App:SelfUrl` isn't what you want users to see in emails — for example, when you use subdomain-based multi-tenancy and want the link to point to the tenant's subdomain. See [Application URLs](../framework/infrastructure/app-urls.md).
### Account Management
`/Account/Manage` page is used to change password and personal information of the user.
@ -56,6 +56,8 @@ Users can leave a tenant. After leaving, the user is no longer a member of that
> When a user leaves and later re-joins the same tenant, the `UserId` does not change and tenant-related data (roles, permissions, etc.) is preserved.
Tenant administrators with the `Identity.Users.Delete` permission can also remove a member from the tenant via the **Remove from tenant** action on the user list. This is a soft removal — the global account stays and the user can be re-invited later, exactly like the self-service Leave.
## Inviting Users to a Tenant
Tenant administrators can invite existing or not-yet-registered users to join a tenant. The invited user receives an email; clicking the link completes the join process. If the user doesn't have an account yet, they can register and join through the same flow.
@ -156,9 +158,12 @@ The following operations can only be performed by a host administrator when Shar
- Enable or disable two-factor authentication
- Change `LockoutEnabled` or `ShouldChangePasswordOnNextLogin`
> `Delete` here means deleting the **global user account**, not removing a user from a single tenant. Removing a member from one tenant is a tenant-level soft operation and is available to tenant administrators — see **Remove from tenant** below.
### What tenant admins can do
- Invite users to the tenant (see the Invitation flow above)
- Remove users from the tenant (soft removal; the global account stays)
- Manage role and organization-unit assignments within the tenant
- View audit / security logs scoped to the tenant
@ -172,4 +177,5 @@ If you plan to migrate an existing multi-tenant application from an isolated str
1. **Uniqueness check**: Before enabling Shared, ensure all existing usernames and emails are unique globally. ABP performs this check when you switch the strategy and reports conflicts.
2. **Tenants with separate databases**: If some tenants use separate databases, you must ensure the Host database contains matching user records in the `AbpUsers` table (and, if you use social login / passkeys, also sync `AbpUserLogins` and `AbpUserPasskeys`) so the Host-side records match the tenant-side data. After that, the framework can create/manage the user-to-tenant associations.
- **Important — each host-side shadow row must have a new primary key (`Id`) different from the tenant user's `Id`.** Generate a fresh `Guid` for every shadow row instead of reusing the tenant user's primary key. The framework relies on this to distinguish a separate-database tenant from a shared-database one; reusing the Id can mask "Leave Tenant" and external login / passkey synchronization on legacy data. The other identifying fields (`UserName`, `Email`, `PasswordHash`, `TenantId`, etc.) should still match the tenant-side row.
$"Either {nameof(AwsBlobProviderConfiguration.Region)} or {nameof(AwsBlobProviderConfiguration.ServiceURL)} must be configured on {nameof(AwsBlobProviderConfiguration)}.");
personDto.GetProperty<string>("Name").ShouldBe("John");//Defined in both classes
personDto.GetProperty<int>("ChildCount").ShouldBe(0);//Not defined in the source, but was set to the default value by ExtensibleTestPersonDto constructor
personDto.GetProperty("CityName").ShouldBeNull();//Ignored, but was set to the default value by ExtensibleTestPersonDto constructor
personDto.HasProperty("Age").ShouldBeFalse();//Not defined on the destination
personDto.HasProperty("Sex").ShouldBeFalse();//Not defined in both classes