Coder Social home page Coder Social logo

jmcdo29 / testing-nestjs Goto Github PK

View Code? Open in Web Editor NEW
2.8K 33.0 367.0 10.82 MB

A repository to show off to the community methods of testing NestJS including Unit Tests, Integration Tests, E2E Tests, pipes, filters, interceptors, GraphQL, Mongo, TypeORM, and more!

License: MIT License

JavaScript 11.22% TypeScript 87.99% HTML 0.39% Dockerfile 0.20% Handlebars 0.07% Shell 0.14%
hacktoberfest nestjs testing examples pipes interceptor rest cqrs graphql typeorm

testing-nestjs's Introduction

Commitizen friendly Continuous Integration Testing Coffee

Nest Logo

testing-nestjs

A repository to show off to the community methods of testing NestJS including Unit Tests, Integration Tests, E2E Tests, pipes, filters, interceptors, GraphQL, Mongo, TypeORM, and more!

Project Structure

Each folder is a fully functional Nest application on its own. All you need to do after cloning the repository is move into the folder, install the dependencies, and test! Or you could just, you know, look at the test on GitHub too, no big deal.

Motivation

I've noticed a lot of people seem to get stuck on testing, and how to do it using the utilities given to us by Nest. Hopefully with a community driven repository of tests it will help others get a better understanding and feel for how to get tests running.

Please Note

This is not necessarily the Nest canonical way to test an application, nor is it the only way in any scenario. I will do my best to show different ways to run tests, but I will more than likely miss certain ways of running the tests, whether it is mocking in a specific way or otherwise. Again, this is a community maintained project and not a part of the official documentation. If you find other ways to test applications, great, I'd love to see them, but please do not think this is the only way.

Running the Project

  1. git clone https://github.com/jmcdo29/testing-nestjs.git
  2. cd testing-nestjs/<folderName>
  3. npm install OR yarn add OR pnpm install
  4. npm run test OR yarn test OR pnpm test

Contributing

Did I miss your favorite topic? Did I miss out on something you absolutely need tested? Well then open an issue, or better yet, a pull request! I'll be happy to look over any topics and try to help figure out how to test them or to merge any PRs that add to the value of the repository. If you do end up making a pull request, please add a screenshot of the test coverage so others can see how well the tests run. The complex-sample branch has a good example.

Change log

The change log can be found on the Releases page.

Authors and license

Jay McDoniel and contributors. Thanks to everyone who's helping with this effort!

MIT License, see the included License.md file.

testing-nestjs's People

Contributors

ddehghan avatar dependabot-preview[bot] avatar dependabot[bot] avatar jeffminsungkim avatar jmcdo29 avatar malcolm-kee avatar micalevisk avatar milesq avatar mnigos avatar neerajkumar161 avatar rostgoat avatar szolowicz avatar tak1n avatar tony133 avatar webbly25 avatar wonderpanda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

testing-nestjs's Issues

[FAILING TEST] Unit testing a NestJS Service that consumes a TypeORM Repository

Describe the bug

I am trying to unit test some services we have in a project that uses TypeORM. We wrap the repositories in services so we can abstract the repo away from the rest of the code and just rely on the services (which are easy to mock).

We couldn't quite get any of our own mocks to work at first, then eventually came across the @golevelup/nestjs-testing module. We've fiddled with that for a bit, found your examples and applied that pattern, but still seem to be having problems. All of our tests that use getRepositoryToken and createMock time out.

To Reproduce
Steps to reproduce the behavior:

Model:

import { Column, Entity, Index, ObjectIdColumn } from 'typeorm';

export class NgbDate {
  @Column() year: number;
  @Column() month: number;
  @Column() day: number;
};

export class DemoBenefit {
  @Column() categoryId: number;
  @Column() subCategoryId: number;
  @Column() quantity: number;
}

@Entity('demoaccounts')
@Index(['cardNumber'], { unique: true })
export class DemoAccount {
  @ObjectIdColumn() _id?: string;
  @Column() authorityId: number;
  @Column() cardNumber: string;
  @Column() householdId?: string;
  @Column() binCode: string;
  @Column() name: string;
  @Column() startDate: NgbDate;
  @Column() endDate: NgbDate;
  @Column() isCardActivated?: boolean;
  @Column(type => DemoBenefit) benefits: DemoBenefit[];
}

Service:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DemoAccount } from './demo-account.model';

@Injectable()
export class DemoAccountService {
  constructor(@InjectRepository(DemoAccount, 'mongo') private readonly repository: Repository<DemoAccount>) {
  }

  async findByCardNumber(cardNumber: string): Promise<DemoAccount | undefined> {
    return this.repository.findOne({ cardNumber });
  }
}

Tests:

import { createMock } from '@golevelup/nestjs-testing';
import { DeepMocked } from '@golevelup/nestjs-testing/lib/mocks';
import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DemoAccount } from './demo-account.model';
import { DemoAccountService } from './demo-account.service';

describe('DemoAccountService', () => {
  let module: TestingModule;
  let service: DemoAccountService;
  let repo: DeepMocked<Repository<DemoAccount>>;
  let app: INestApplication;

  beforeEach(async () => {
    jest.setTimeout(30000);
    module = await Test.createTestingModule({
      providers: [
        DemoAccountService,
        {
          provide: getRepositoryToken(DemoAccount, 'mongo'),
          useValue: createMock<Repository<DemoAccount>>(),
        },
      ],
    }).compile();

    service = module.get(DemoAccountService);
    repo = module.get(getRepositoryToken(DemoAccount, 'mongo'));
    app = module.createNestApplication();
    await app.init();
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('findByCardNumber()', () => {
    it('should return entity when found by card number', async () => {
      const demoAccount: DemoAccount = {
        authorityId: 15,
        cardNumber: '1234569999999999',
        name: 'TEST DEMO CARD',
        binCode: '123456',
        startDate: {  year: 2020, month: 3, day: 1 },
        endDate: { year: 2020, month: 3, day: 31 },
        benefits: [
          { categoryId: 1, subCategoryId: 0, quantity: 2 },
          { categoryId: 2, subCategoryId: 0, quantity: 4 },
        ]
      };

      repo.findOne.mockResolvedValue(demoAccount);

      expect(await service.findByCardNumber('1234569999999999')).toEqual(demoAccount);
    });
  });
});

Simple NestJS project with this service/entity and test should be sufficient to replicate the problem.

Expected behavior
Unit tests that run in a timely manner without timing out.

Desktop (please complete the following information):

  • OS: MacOS
  • Version: 7.5.6

Additional context

Error: Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.
Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.
    at mapper (/Users/jonrista/contracts/wicshopper-benefits-server/node_modules/jest-jasmine2/build/queueRunner.js:27:45)
    at /Users/jonrista/contracts/wicshopper-benefits-server/node_modules/jest-jasmine2/build/queueRunner.js:75:41
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

[NEW TEST] WebSockets

Feature Test To Be Requested

A test repository showing how to test web sockets could be really useful for some people. Full End to End testing too if possible

[FAILING TEST] Issue to setup test module

Hello I'm very new to testing and I asked in stackoverflow already but didn't receive any answer yet :( (https://stackoverflow.com/questions/65321562/unit-tests-in-nestjs?noredirect=1#comment115481831_65321562)

Basically I have following setup for test:

import { Test, TestingModule } from '@nestjs/testing';
import { BlockchainModule } from '../blockchain/blockchain.module';

import { BlockchainService } from '../blockchain/blockchain.service';
import { FaucetModule } from '../faucet/faucet.module';
import { FaucetService } from '../faucet/faucet.service';
import { UserController } from './user.controller';

import { UserService } from './user.service';

describe('UserController', () => {
    let controller: UserController;
    let userService: UserService;
    let faucetService: FaucetService;
    let blockchainService: BlockchainService;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            imports: [BlockchainModule, FaucetModule],
            controllers: [UserController],
            providers: [UserService, FaucetService, BlockchainService],
        }).compile();

        controller = module.get<UserController>(UserController);
        userService = module.get<UserService>(UserService);
        faucetService = module.get<FaucetService>(FaucetService);
        blockchainService = module.get<BlockchainService>(BlockchainService);
    });

    // it('should be defined', () => {
    //     expect(controller).toBeDefined();
    // });
});

And throws following error: Cannot find module 'src/config/app.config' from 'modules/blockchain/blockchain.service.ts'
This is how AppConfig is imported in blockchain service:

blockchain.service.ts:

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Wallet, providers, utils, Overrides } from 'ethers';
import { AppConfig } from 'src/config/app.config';
import { OpnCash } from './contract/OpnCash';
import { OpnCashFactory } from './contract/OpnCashFactory';

import { Erc20Factory } from './contract/Erc20Factory';

@Injectable()
export class BlockchainService {
    private contract: OpnCash;
    private provider: providers.BaseProvider;

    constructor() {
        this.contract = new OpnCashFactory().attach(AppConfig.blockchain.contract);
        this.provider = new providers.JsonRpcProvider(AppConfig.blockchain.rpcUrl, AppConfig.blockchain.chainId);
    }

    async sendTransaction(from: string, to: string, amount: number, options?: Overrides) {
        try {
            this.contract = this.contract.connect(new Wallet(from, this.provider));
            const tx = await this.contract.transfer(to, utils.parseEther(String(amount)), { ...options, gasPrice: 0 });
            const result = await tx.wait();
            return result.transactionHash;
        } catch (err) {
            if (err.code === 'UNPREDICTABLE_GAS_LIMIT') {
                throw new HttpException('Unsufficient amount.', HttpStatus.BAD_REQUEST);
            }
            throw new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

My question is how to resolve this issue so the test case have access to AppConfig

README refers to non-existing cat.integration.spec.ts

As I was looking for some integration test inspiration I found this promising repo and even a reference to cat.integration.spec.ts in the README. Unfortunately it seems the actual file has been removed in fa73e57. ๐Ÿ˜ข

Unless that was a mistake I suppose it should be fixed in the README. Out of curiosity, why was it removed?

[NEW TEST] TypeORM

Feature Test To Be Requested
Add test cases for TypeORM.

This is already in the works but is more to help me track what needs to be done.

gitads link doesn't work

I'm new to this repo so I started by reading the README.

Not sure yet what's a proper fix to this by reading this paragraph:

testing-nestjs is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial

is a bit confusing because there isn't any clickable links or embedded images being shown. After some investigation I noticed the gitads link:

<a href="https://tracking.gitads.io/?repo=testing-nestjs">
 <img src="https://images.gitads.io/testing-nestjs" alt="GitAds"/>
</a>

Not sure what was there before but it doesn't seem to work at the moment:

Not found - Request ID: 89820bc6-de74-4e79-bbb0-ccfeb24a8e25-1826118

[NEW TEST] Custom Decorator Testing

Unit Tests for Custom Decorators

I created a custom decorator which can be added to Service methods for Caching Data.
But unfortunately cannot find any simple documentation which can provide a way we can test Custom Decorators.
It would be great if you can add something around it.

I found this from the official Github code as a starting point, but since this is such a nice place for all the nest js testing stuff, adding something around decorators would be a plus -https://github.com/nestjs/nest/blob/master/packages/common/test/decorators/cache.decorator.spec.ts

[NEW TEST] Asyncronous and Observables

Feature Test To Be Requested
A little less related to NestJS overall, but still useful would be examples of testing async/await and RxJS Observbales code with jest. Especially with creating re-usable observers for Observables to make tests easily configurable and less duplicated.

[TypeORM sample unit test question]

Feature Test To Be Requested
Sorry for open a qustion issue.
I read the code about apps/typeorm-sample/src/cat/cat.service.spec.ts
and I realize that the test case is repeatting the steps as we develop, it means we need to know very detail about the implementation.
I serach a lot about Nestjs testing with TypeORM, and find an issue comment it address that

I like to write assertions on the result rather than on the way the result was obtained

And I agree with that. IMO, unit test should be simple and dump with assertions about input and output, not the steps how we develop.

Hopefully all you guys could give your comments about that if you see the issue

Thanks for the great repo, it helps me a lot

Multiple mocked dependencies with the same content

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I'm trying to manually mock 2 dependencies to unit test a specific service, but while one is correctly mocked, jest seems to be attributing the same content to the other dependency. The beginning of the test code is as follows:

jest.mock('../../user/user.service');
jest.mock('../../rent/rent.service');

describe('RatingService', () => {
    let service: RatingService;
    let repository: MockType<Repository<RatingORM>>;

    let userService: UserService;
    let rentService: RentService;

    let user: UserORM;

    beforeEach(async () => {

        user = userStub({ random: true });

        const module = await Test.createTestingModule({
            providers: [
                RatingService,
                UserService,
                RentService,
                { provide: getRepositoryToken(RatingORM), useValue: repositoryMockFactory(ratingStub()) },
            ],
        }).compile();

        service = module.get<RatingService>(RatingService);
        repository = module.get(getRepositoryToken(RatingORM));

        userService = module.get<UserService>(UserService);
        rentService = module.get<RentService>(RentService);

        jest.clearAllMocks();
    });
}

I've ommited the tests as the file is too long.

Down here are the relevant mocks of each service:

import { userStub } from "../test/stubs/user.stubs";

export const UserService = jest.fn().mockReturnValue({
    byId: jest.fn().mockResolvedValue(userStub()),
    byEmail: jest.fn().mockResolvedValue({}),
    genericFetch: jest.fn().mockResolvedValue({}),
    create: jest.fn().mockResolvedValue({}),
    save: jest.fn().mockResolvedValue(userStub()),
    resolveUserRating: jest.fn().mockResolvedValue(undefined),
});
export const RentService = jest.fn().mockReturnValue({
    extract: jest.fn().mockResolvedValue({}),
    create: jest.fn().mockResolvedValue({}),
    approve: jest.fn().mockResolvedValue({}),
    cancel: jest.fn().mockResolvedValue({}),
});

When printing the userService and rentService objects after getting them from the testing module, both have all functions from the rent service.

The mock file from userService and rentService are entirely different and reside in completely different locations. I've checked and tested all imports and exports, and all seems correct.

I have no idea what's happening here. Can somebody help me?

Minimum reproduction code and/or steps to reproduce

No response

Expected behavior

1 - Mocks to be made correctly
2 - Functions to be called correctly
3 - Tests to be passed

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Additional context

No response

[NEW TEST] Testing for interceptor failure

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

I was using your CatInterceptor test as a template for a request interceptor test.

It was not clear how to test for an expected failure. Below is sketch of the test I created:

class FailingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    throw new Error();
  }
}

const interceptor = new FailingInterceptor();

// create the mock CallHandler for the interceptor
const next = {
  handle: () => EMPTY,
};

it('should fail', () => {
  const ctxMock = createMock<ExecutionContext>({
    switchToHttp: () => ({
      getRequest: () => ({
        headers: {},
      }),
    }),
  });
  expect(() =>
    interceptor
      .intercept(ctxMock, next)
      .subscribe({ complete: () => fail() }),
  ).toThrowError(Error);
  expect(fnAfterFailure).not.toHaveBeenCalled();
});

I also discovered that failures in the Observable subscriber would result in test timeouts. That is, the test would fail but it would also timeout because done was never called.

To be resilient in the event of unexpected failure, I think the cat interceptor test should be modified:

    it('should successfully return', (done) => {
      interceptor.intercept({} as any, next).subscribe({
        next: (value) => {
          try {
            expect(value).toEqual({ data: returnCat });
          } catch(error) {
            fail(error);
          }
        },
        error: (error) => {
          fail(error);
        },
        complete: () => {
          done();
        },
      });
    });

[NEW TEST] Sequelize transactions

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

The sequelize-sample is really awesome, but we're using Sequelize Transactions in our codebase and by doing so we have to mock the Sequelize transaction() method or Nest will throw dependency errors:

Nest can't resolve dependencies of the CatService (CatEntityRepository, ?). Please make sure that the argument Sequelize at index [5] is available in the RootTestModule context.

Potential solutions:
- Is RootTestModule a valid NestJS module?
- If Sequelize is a provider, is it part of the current RootTestModule?
- If Sequelize is exported from a separate @Module, is that module imported within RootTestModule?
  @Module({
    imports: [ /* the Module containing Sequelize */ ]
  })

I've looked through the NestJS documentation and Discord but I couldn't find any good examples of how to do this because if I mock the Sequelize transaction like this, I don't get the value from my service call:

        {
          provide: Sequelize,
          useValue: {
            transaction: jest.fn(() => Promise.resolve()),
          },
        },

The Nest docs state to use a helper factory class but I couldn't find a good example of this either.

[NEW TEST] KnexJs Sample test

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

It would be great if we have another branch new test of KnexJs

[NEW TEST] Microservices

Feature Test To Be Requested

Showing how to test microservice could be useful, especially in an e2e context

TypeORM and e2e testing

I think, full e2e testing with database is an interesting problem. But in TypeORM Sample there is no cats.e2e-test.

If we don't mock the DB and make e2e tests mostly near to real environment, there are some interesting things:

  • DB creation (sync, migrations, seeds, dumps)
  • Running in parallel (databeses must be separated. More intersting if we use not sqlite with in-memory)

It seems to me, that's important part of testing, but may be a bit of overhead. What do you think?

[NEW TEST] Tests for mikro-orm

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

Hey,

This is a great repo and my goto whenever I am writing tests.
Since the repo has examples for most orms, I think it would be good to include an example illustrating one with mikro-orm

I would be happy to work on the examples.

[NEW TEST] - (Contract Testing) - Incorporate NestJS Consumer Driven Contract testing with nestjs-pact

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

Hey,

Great repo <3

The member of the Pact OSS community recently developed with a NestJS Pact adapter to allow for easy consumer driven contract testing with Pact in a NestJS project.

You can see the repo here https://github.com/omermorad/nestjs-pact

and find our how Pact and Consumer Driven Testing works here

I would be happy to work on the examples.

cc: @omermorad

I can't seem to make the tests fails anywhere so far

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I have bee adding failure expect to tests in simple-sample as well as graphql-sample

        expect(0).toEqual(42);

But the tests keeps not failing. I've also changed 200 to 404 and cats to null, and so far, no attempts at breaking testes have had any effect, which is worrisome for the test actual working state

Minimum reproduction code and/or steps to reproduce

Adding

        expect(0).toEqual(42);

In varous test and pnpm test

For example :
simple-test

import { Test, TestingModule } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
import { INestApplication } from '@nestjs/common';

const requestFunction = (url: string, data: string, app: INestApplication) =>
  request(app.getHttpServer()).get(url).expect(200).expect(data);

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = module.createNestApplication();
    await app.init();
  });

  describe('/ (GET)', () => {
    it('/ (GET)', () => {
      expect(0).toEqual(42);
      return requestFunction('/', 'Hello, World!', app);
    });
    it('/?name=Tester', () => {
      return requestFunction('/?name=Tester', 'Hello, Tester!', app);
    });
  });
});

Expected behavior

The test should fail after having been tempered with badly

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Additional context

No response

[NEW TEST] GraphQL E2E

A simple test set to show off e2e testing with GraphQL. This can be an update to the typeorm-graphql-sample or a new graphql-sample, but it needs to show e2e.

Add code comment for documenting the tests.

Add code comment for documenting the tests.

I think adding a code comment to the test suite is a good idea for code readability and I think this will benefit a lot more people in this regard. If this is something that is acceptable to the project I can contribute this to the existing tests.

[NEW TEST] Custom Auth Guard Tests

Hi,

thanks for this repo - it helps a lot in figuring out how to test!

I am currently trying to write a test for an UserAuthGuard which extends the default AuthGuard and uses a custom strategy (Firebase Auth).

It basically just calls super.canActivate() to trigger the Firebase Auth and then checks if some decorators are set. My main concern is the super.canActivate() --> How can I mock that in a unit test? I guess this is rather jest specific, but I could not find anything useful there, too.

@Injectable()
export class UserAuthGuard extends AuthGuard('firebase')
  implements CanActivate {
  constructor(private reflector: Reflector) {
    super();
  }

  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    await super.canActivate(context);
    const request = this.getRequest(context);
    const user: AuthUser = request.user;

    if (user?.admin) return true;

    // adminOnly
    const adminOnly = this.reflector.get<boolean>(
      'adminOnly',
      context.getHandler(),
    );
    if (adminOnly) return false;

    // notEmployee
    const notEmployee = this.reflector.get<boolean>(
      'notEmployee',
      context.getHandler(),
    );
    if (notEmployee && user?.employee) return false;

    return true;
  }
}

Test against Solidity smart contracts

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

I would like an example to test against smart contracts.
On my application, I have a smart contract that needs to be called to check some data in the contract. I need this data to reach my back-end application somehow.

Thing is, I could test the contract against a testnet, but it would take too long to respond. And it would depend on the testnet being live.

The best way to do it would be using something like what hardhat does, but I have no idea how it implements a "local" blockchain for testing and how I can replicate it on nestjs testing environment. If anyone have an idea, please suggest me. I might implement it. Because for my use case it is really necessary.

Unable to commit the file in file-up-and-down-sample

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I was doing some type assertion fix in the file, after doing that when I tried to commit the file, .eslintrc.json file causing the issue and unable to commit the file. You can check the screenshot I have shared. I tried installing the package as well as mentioned in the terminal, but it didn't work. Please let me know if I'm missing anything.

image

Minimum reproduction code and/or steps to reproduce

No response

Expected behavior

File should commit after making changes.

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Additional context

No response

Create an E2E test for a controller method with an @Render annotation

I have my application setup to render pug templates. When writing an E2E test for a controller method that has a @Render annotation, we need to setup the view engine. Otherwise, you get this exception:

[Nest] 87500   - 12/01/2019, 9:38:18 PM   [ExceptionHandler] No default engine was specified and no extension was provided. +4ms
Error: No default engine was specified and no extension was provided.
    at new View (/Users/raftheunis/Development/git/LMG/lmg-proxy-nestjs/node_modules/express/lib/view.js:61:11)
    at Function.render (/Users/raftheunis/Development/git/LMG/lmg-proxy-nestjs/node_modules/express/lib/application.js:570:12)
    at ServerResponse.render (/Users/raftheunis/Development/git/LMG/lmg-proxy-nestjs/node_modules/express/lib/response.js:1012:7)
    at ExpressAdapter.render (/Users/raftheunis/Development/git/LMG/lmg-proxy-nestjs/node_modules/@nestjs/platform-express/adapters/express-adapter.js:29:25)
    at RouterResponseController.render (/Users/raftheunis/Development/git/LMG/lmg-proxy-nestjs/node_modules/@nestjs/core/router/router-response-controller.js:24:29)
    at process._tickCallback (internal/process/next_tick.js:68:7)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Maybe you can setup something like that in your testing suite?

Thanks!

[NEW TEST] MongoDB

Feature Test To Be Requested
Add tests for MongoDB.

This is already a planned effort, just creating an issue to track

[NEW TEST] Bull

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

Add some examples using nestjs bull queue

Question about your remark on mongo-testing.

Hi Jay
In your comments above this line you argue not using save method because it is hard to mock.
I came across this because I was indeed trying to mock it and I don't get it to work.
Can you elaborate on why you can't just do:
jest.spyOn(model, 'save').mockResolvedValueOnce({...});
But the following is no problem?
jest.spyOn(model, 'create').mockResolvedValueOnce({...});

[FAILING TEST] The try catch tests are passing even with not getting to the evaluation

Describe the bug

it('should throw and error for a bad id', () => {
try {
service.getById(15874);
} catch (err) {
expect(err.message.message).toBe('No cat found with id 15874.');
expect(err.message.error).toBe('Bad Request');
}
});

To Reproduce
just remove the line in the try block
Expected behavior
Without anything in the try block this test should fail because it expects an error to be thrown. But it passes because it never gets to the catch part
Desktop (please complete the following information):

  • OS: [e.g. Windows, MacOS, Linux (which distro)] MacOS
  • Version: [Which version of Nest are you running?]
    "@nestjs/common": "^6.11.11",
    "@nestjs/core": "^6.11.11",

Could be fixed by throwing an error inside the try block after the service call.

throw new Error('Test was force-failed');
or one of many other methods listed here https://codewithhugo.com/jest-force-explicitly-fail-test/

[NEW TEST] CQRS

Feature Test To Be Requested
Examples on how to test the CQRS framework with NestJS

[FAILING TEST] Dangerous example code

Describe the bug
I'd like to point out that there an insecure code from cat.service.spect.ts file in typeorm-sample project. (Perhaps, there might be more..)

To Reproduce
Steps to reproduce the behavior:

const catArray = [
  new Cat(testCat1, testBreed1, 4, 'uuid1'),
  new Cat('Test Cat 2', 'Test Breed 2', 3, 'uuid2'),
  new Cat('Test Cat 3', 'Test Breed 3', 2, 'uuid3'),
];

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        CatService,
        {
          provide: getRepositoryToken(Cat),
          useValue: {
            find: jest.fn().mockResolvedValue(catArray),
          },
        },
      ],
    }).compile();
});

describe('getAll', () => {
  it('should return an array of cats', () => {
    expect(service.getAll()).resolves.toEqual([
      new Cat('Different', 'Value', 4, 'uuid1123213'),
      new Cat('Test Cat 2', 'Test Breed 2', 3, 'uuid2'),
      new Cat('Test Cat 3', 'Test Breed 3', 2, 'uuid3'),
    ]);
  });
});

It throws the following error below, but the test still pass.
(node:40862) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

For some reason, if we change the value of catArray, the test code turns out to be pointless.

Expected behavior

describe('getAll', () => {
  it('should return an array of cats', async () => {
    expect(await service.getAll()).toEqual([
      new Cat('Different', 'Value', 4, 'uuid1123213'),
      new Cat('Test Cat 2', 'Test Breed 2', 3, 'uuid2'),
      new Cat('Test Cat 3', 'Test Breed 3', 2, 'uuid3'),
    ]);
  });
});

Jay, if you think this needs to be fixed then I can get my hands dirty.

Desktop (please complete the following information):

  • OS: MacOS
  • Version: 6.11.8 (latetest)

Additional context
Add any other context about the problem here.

[e2e tests for mongo-sample]

Just a e2e tests using mongo
A clear and concise description of what feature you want to be shown tests for (e.g. Authentication):
I tried to create e2e tests by when i started it it's connected to db and adding this data from tests to my db. Should i use mockingoose?

[NEW TEST] Automated E2E Testing

Use Dockerfiles and docker-compose to allow for E2E tests to be run via GitHub Actions. This will allow for even better tracking of changes to the NestJS Ecosystem and will help others know the E2E tests are working properly

[NEW TEST]some test cases for axios request?

Feature Test To Be Requested
A clear and concise description of what feature you want to be shown tests for (e.g. Authentication):
Hi Jay,

Could you add some test cases for axios request?

I am not sure if I should use mock axios or real axios request in this case when test in e2e

Thanks

Prisma transactions and rollbacks now available

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

Use the Transactions and Rollback Transactions from Prisma to complete the test code @ this path: apps/prisma-sample/test/cats.e2e-spec.ts

Create a Wiki

It might be nice to have a Wiki set up to help people better understand the overall idea of the repository. Anyone is free to help out with this

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.