Ready to get started?

Join Adocasts Plus for $8/mo, or sign into an existing Adocasts Plus account, to get access to all of our lessons.

robot mascot smiling

Pragmatic Testing in AdonisJS with Japa #3.1

Introduction to Mocks & Dependency Swapping

In This Lesson

We'll cover Unit Testing services with dependencies. Learn to create a mock for a dependency and use the AdonisJS IoC Container to replace the real dependency with your mock, ensuring isolated and side-effect-free testing.

Created by
@tomgobich
Published

Notes Used to Craft this Lesson

So, what about if our service has a dependency? For example, our NotificationService depends on the AdonisJS logger.

// app/services/notification_service.ts
import { inject } from "@adonisjs/core";
import { Logger } from "@adonisjs/core/logger";

@inject()
export default class NotificationService {
  constructor(protected logger: Logger) {} // 👈

  /**
   * Simulates sending a notification with the given message.
   * This is a placeholder for an actual notification service.
   * It will log the message and then wait for 5 milliseconds before resolving.
   *
   * @param message - The message to be sent in the notification.
   */
  async send(message: string) {
    this.logger.info("Simulating notification %s", message);

    await new Promise((resolve) => setTimeout(resolve, 5));
  }
}

Join the Discussion 0 comments

Create a free account to join in on the discussion
robot comment bubble

Be the first to comment!