nest icon indicating copy to clipboard operation
nest copied to clipboard

Example for running Tests

Open Mark-McCracken opened this issue 9 years ago • 22 comments

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

Mark-McCracken avatar May 19 '17 11:05 Mark-McCracken

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 ?

thomrick avatar May 19 '17 14:05 thomrick

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!!

Mark-McCracken avatar May 20 '17 11:05 Mark-McCracken

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"
  }

thomrick avatar May 22 '17 07:05 thomrick

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.

kamilmysliwiec avatar May 24 '17 10:05 kamilmysliwiec

Hey @kamilmysliwiec,

I'm on it ;-)

thomrick avatar May 24 '17 10:05 thomrick

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

kamilmysliwiec avatar May 24 '17 10:05 kamilmysliwiec

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 avatar May 26 '17 18:05 thomrick

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 avatar May 26 '17 19:05 thomrick

@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. ;-)

thomrick avatar May 26 '17 20:05 thomrick

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.

kamilmysliwiec avatar Jul 16 '17 11:07 kamilmysliwiec

@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 )

joshwiens avatar Aug 09 '17 06:08 joshwiens

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

kamilmysliwiec avatar Sep 12 '17 15:09 kamilmysliwiec

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)?

aljazerzen avatar Sep 25 '17 11:09 aljazerzen

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.

joshwiens avatar Sep 25 '17 13:09 joshwiens

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?

aljazerzen avatar Sep 25 '17 13:09 aljazerzen

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 )

joshwiens avatar Sep 25 '17 14:09 joshwiens

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...

aljazerzen avatar Sep 25 '17 14:09 aljazerzen

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

joshwiens avatar Sep 25 '17 14:09 joshwiens

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

artworkad avatar Oct 20 '17 14:10 artworkad

@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;
  });
});

aljazerzen avatar Oct 20 '17 14:10 aljazerzen