Testing API Rules
In Remult, automated tests run as if they are executing directly on the backend. This can make it challenging to test API rules, which typically involve permissions and access control that rely on simulating API calls. To address this, you can use the TestApiDataProvider
, which simulates an API environment for each database operation in your tests.
Code Example: Authorization Tests with TestApiDataProvider
The example below demonstrates how to test API rules, including user authentication and authorization, using TestApiDataProvider
:
Code Explanation
-
Test Setup with
beforeEach
:- we set up the test environment to use
TestApiDataProvider
, simulating an API call for each database operation. - We also create an initial task in the database to test authorization logic on existing data.
- we set up the test environment to use
-
Testing API Rules:
- Each test simulates different user scenarios to verify the
delete
permission on tasks:- Non-Authenticated Users: If
remult.user
is set toundefined
, the test verifies that unauthenticated users cannot delete tasks. - Non-Admin Users: With
remult.user
set to an authenticated but non-admin user, the test expects aForbidden
error when attempting deletion. - Admin Users: An authenticated admin user should have deletion access, and the test confirms that the task count decreases accordingly.
- Non-Authenticated Users: If
- Each test simulates different user scenarios to verify the
Testing SQL-Related Logic
For SQL-based tests, you can use the SqlDatabase.LogToConsole = true
setting to see SQL queries and understand the underlying operations during tests.
Using these techniques allows you to simulate real API operations within tests, ensuring robust access control and proper handling of user permissions in your application.
- Installing dependencies
- Starting http server