npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nest-spectator

v0.0.10

Published

Auto-mocking for Nestjs providers

Downloads

5,639

Readme

Auto-mocking for Nestjs providers

🏠 Homepage

Author

👤 Jay Bell [email protected]

Usage

See packages/nest-spectator/__tests__ for reference:

Let's assume you we have the following 2 different Nestjs services:

@Injectable()
class PrimaryService {
  constructor(secondaryService: SecondaryService) {
  }

  testFunction(): string {
    return 'test';
  }
}

and

@Injectable()
class SecondaryService {
}

and this controller:

@Controller()
class PrimaryController {
  constructor(primaryService: PrimaryService) {
  }
}

Currently we have something like:

import { Test } from '@nestjs/testing';
import { PrimaryController } from './primary.controller';
import { PrimaryService } from './primary.service';
import { SecondaryService } from './secondary.service';

describe('PrimaryController', () => {
  let primaryController: PrimaryController;
  let primaryService: PrimaryService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
        controllers: [PrimaryController],
        providers: [PrimaryService, SecondaryService],
      }).compile();

    primaryService = module.get<PrimaryService>(PrimaryService);
    primaryController = module.get<PrimaryController>(PrimaryController);
  });
});

Which is fine for small projects but as your code base grows you could have many injections in your classes constructor that you are testing. Assuming you plan on creating mocks for the services injected into PrimaryController classes or you want to spy on the classes methods of PrimaryService your code can start to grow more and more for each time you have a new spec file.

If you do not mock our your services and instead just want to spy on them, your spec files will grow very large because each service you provider in the Test.createTestingModule will need to have all of it's services injected as well.

You can see the effect of this in the sample above, SecondaryService is injected because PrimaryService injects it which in turn is injected into PrimaryController

If you are wanting to create mocks for each of these services injected in your class being tested then it would look something like this:

import { Test } from '@nestjs/testing';
import { PrimaryController } from './primary.controller';
import { PrimaryService } from './primary.service';
import { SecondaryService } from './secondary.service';

const mockPrimaryService = {
    testFunction: () => {}
}

class MockPrimaryService {
    testFunction(): void {
    }
}

describe('PrimaryController', () => {
  let primaryController: PrimaryController;
  let primaryService: PrimaryService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
        controllers: [PrimaryController],
        providers: [
            {provide: PrimaryService, useValue: mockPrimaryService}
            // OR
            {provide: PrimaryService, useClass: MockPrimaryService}
        ],
      }).compile();

    primaryService = module.get<PrimaryService>(PrimaryService);
    primaryController = module.get<PrimaryController>(PrimaryController);
  });
});

Now you will have to maintain these mock objects for each of your services and ensure you provide over your implementation services in each of your spec files.

This is where nest-spectator comes in, inspired by @ngneat/spectator for Angular, nest-spectator creates a layer on top of the @nestjs/testing Test.creatingTestingModule to provide the functionality to auto mock your services so that your module instantiation in tests turns into:

beforeEach(async () => {
  module = await createTestingModuleFactory(
      {
        imports: [],
        controllers: [PrimaryController],
        providers: [PrimaryService],
        mocks: [PrimaryService]
      },
  ).compile();
});

The createTestingModuleFactory accepts all the same values as the Test.createTestingModule function except that there is an option property mocks?: Array<Type<any>> that will accept the providers you want to auto mock. This function will return the same value (TestingModuleBuilder) as Test.createTestingModule will which means we just call .compile() on it after to get our testing module.

If we need access to our services provided to this testing module we get them the same way as we would before since we just have a TestingModule.

const primaryService = module.get<PrimaryService>(PrimaryService);

If PrimaryService was included in the mocks array during test module instantiation than it will be an object that mirrors the structure of your class as if it was provided normally except that the methods, getters and setters will all be jest Spys themselves.

When providing PrimaryService in the mocks array and using module.get<T>(T) to get the instance of the provider it will return SpyObject<PrimaryService> instead of just PrimaryService.

This package is still in alpha so there way be unintended side effects or gaps in the logic. If there is anything you would like to see include please feel free to open an issue.

🤝 Contributing

Contributions, issues and feature requests are welcome!Feel free to check issues page. You can also take a look at the contributing guide.

Show your support

Give a ⭐️ if this project helped you!


This README was generated with ❤️ by readme-md-generator