nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.69k stars 7.63k forks source link

Example for running Tests #75

Closed Mark-McCracken closed 7 years ago

Mark-McCracken commented 7 years ago

Can anyone provide an example of how they've managed to run testing using nest?

I don't really understand the setup involved in getting a test runner to work, to run the tests I create

thomrick commented 7 years ago

Hey @Mark-McCracken,

In my case I use Jest and I wrote this piece of example:

describe('RegistrationService', () => {
  let service: RegistrationService;

  beforeEach(() => {
    Test.createTestingModule({
      components: [
        RegistrationService
      ]
    });
  });

  beforeEach(() => {
    service = Test.get(RegistrationService);
  });

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

For Jest I had to add this piece of configuration inside package.json:

"jest": {
    "transform": {
      "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.ts$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "json"
    ]
  }

And use these devDependencies:

"devDependencies": {
    "@types/jest": "^19.2.3",
    "@types/node": "^7.0.18",
    "jest": "^20.0.3",
    "ts-jest": "^20.0.3",
    "typescript": "^2.3.2"
  }

Does it answer your question ?

Mark-McCracken commented 7 years ago

yeah that seems to work pretty well! Thanks! Only problem I have now is that jest is trying to run all of my client side tests for my angular code, which I don't need it to do as I've already got ng test for that, and it isn't executing them correctly anyway. I tried to do this in my package.json

    "testRegex": "(/__server__/.*|\\.(test|spec))\\.ts$",

as all my test files are kept beside their relevant files. It said I didn't have a tsconfig.json in my project root directory, which I don't, because my project contains my server side code and my angular app, so I copied the server side one into the base (btw, does nest support extending the tsconfig.json file?) and it seems to run all tests, rather than just server ones.

However, with Webstorm, now that jest is set up, I can just click on the test inside my editor and see it run that test, which is super handy.

Thanks for your help!!

thomrick commented 7 years ago

Hey @Mark-McCracken,

You can also use the next test suite:

"devDependencies": {
    "@types/chai": "^3.5.2",
    "@types/mocha": "^2.2.41",
    "@types/node": "^7.0.18",
    "@types/sinon": "^2.2.2",
    "@types/supertest": "^2.0.0",
    "chai": "^3.5.0",
    "mocha": "^3.4.1",
    "node-mocks-http": "^1.6.2",
    "sinon": "^2.2.0",
    "supertest": "^3.0.0",
    "ts-node": "^3.0.4",
    "typescript": "^2.3.2"
  }

And execute them with this command:

"scripts": {
    "test": "mocha --compilers ts-node/register src/**/*.spec.ts"
  }
kamilmysliwiec commented 7 years ago

Hi @Mark-McCracken, I'll create some testing examples when I have some free time. Of course, if there is someone who want to create one, it would be awesome.

thomrick commented 7 years ago

Hey @kamilmysliwiec,

I'm on it ;-)

kamilmysliwiec commented 7 years ago

@ThomRick, awesome. Let me know when you finished - I'll add repo to Examples section. :)

thomrick commented 7 years ago

Ok I can write tests on the current examples to start. Do you want to use different test frameworks or just the current ones (mocha chai sinon) ?

thomrick commented 7 years ago

Hey @kamilmysliwiec, Maybe the master branch is not up to date because typescript compile fail when running unit tests... Or maybe the up to date branch is not master and I have to start from it to write test examples ?

thomrick commented 7 years ago

@kamilmysliwiec I've started a repo on my own github account with mocha testing framework here : https://github.com/ThomRick/nest-test-mocha-example

We will integrate it later if you want. ;-)

kamilmysliwiec commented 7 years ago

There's a plan to create a directory which would contain as much as possible use-cases and examples of nest. Hope to finish it asap.

joshwiens commented 7 years ago

@Mark-McCracken - To make life a bit simpler, give the Jest configuration it's own tsconfig.spec.json which extends tsconfig.json

Exclude **/*.spec.ts in the core tsconfig.json Include **/*.spec.ts in the Jest tsconfig.spec.json

This approach allows your tests to live with their features, will still work with things like the Jest extension for VSCode while simplifying runtime & distribution builds ( don't want specs in your deployment build )

kamilmysliwiec commented 7 years ago

Hi @Mark-McCracken, There's an example https://github.com/kamilmysliwiec/nest/tree/master/examples/01-cats-app Also brief description in the docs: http://www.docs.nestjs.com/advanced/unit-testing http://www.docs.nestjs.com/advanced/e2e-testing Thanks

aljazerzen commented 7 years ago

When writing code with WebStorm, typescript returns a few errors in cats.e2e-spec.ts file. When running tests, this is not a problem since typescript is compiled through ts-jest and not directly by running tsc.

Errors are annoying - is there any way to get rid of them (or did I just set up something wrong)?

joshwiens commented 7 years ago

Save yourself the pain and just use VSCode? I've never had any of the above issues testing either NestJS or Angular via Jest.

For reference, i'm not trying to be a smart ass. I just know I have personally been much more productive after leaving the Java based IDE's behind.

aljazerzen commented 7 years ago

It is not a direct problem with WebStorm - if you compile cats.e2e-spec.ts file with vanilla TypeScript you will get errors.

Does VSCode not show any errors?

joshwiens commented 7 years ago

I don't transpile my specs / e2e tests in my builds as it's not necessary & like you said, ts-jest takes care of the test runs. That said, my boilerplate for server side projects is a bit more complex than most I have seen.

What you are describing also happens with the .spec files if you just run them through tsc though I don't personally think you need to run either test type though tsc ( unless I am missing something )

aljazerzen commented 7 years ago

So you don't have VSCode checking the code as you write? No underlining the mistakes you make?

Hmm, well I could just disable live inspection in WebStorm and call it a day...

joshwiens commented 7 years ago

I don't get errors inside vscode, only if I explicitly run the files through tsc.

screen shot 2017-09-25 at 9 33 56 am

artworkad commented 7 years ago

@aljazerzen https://stackoverflow.com/q/46848802/401025

aljazerzen commented 7 years ago

@ArtworkAD thanks, but I end up building my own script for running tests using Mocha and Should.js.

For anyone interested, I use script test.js to run all that:

const
  Mocha = require('mocha'),
  path  = require('path');

process.env.NODE_ENV = 'test';

require('ts-node/register');

// Suppress Nest.js output.
let write = process.stdout.write;

process.stdout.write = () => null;

// Start app
require('./src/server').app.then(app => {
  process.stdout.write = write;
  console.log('Application started.');

  global.server = app;
  global.clientAuth = '';

  const mocha = new Mocha();
  const testDir = 'test';
  const testFiles = [
    'user.spec.ts'
  ];

  testFiles.forEach(file => mocha.addFile(path.join(testDir, file)));

  mocha.run(function ( failures ) {
    app.close();
    process.exit(failures);
  });
});

and user.spec.ts then looks like:

import * as request from 'supertest';
require('should');

declare const server;
declare let clientAuth;

describe('user', async () => {

  it(`should be able to register`, async () => {
    let res = await request(server)
      .post('/api/v1/register')
      .send({ username: ..., password: ... })
      .expect(200);
    should.exist(res.body.data.accessToken);
    clientAuth = res.body.data.accessToken;
  });
});
psaunders commented 6 years ago

If you're reading this a little later, there is actually a working example with testing in the repo: https://github.com/nestjs/nest/tree/master/examples/01-cats-app

I think that it'd be good if the demo project repo just had all these and added more.

lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.