Search code examples
mocha.jsnestjssinontypeorm

Can't test class containing import nestJS


I am trying to build unit test for my service implemented in nodeJS. I understood that I can't use import in my test files so I used only require in my test files:

const typeorm = require("typeorm");
const DeviceService = require("./device.service.ts");
const Device = require("./entities/device.entity.ts");
const CreateDeviceDto = require("./dto/create-device.ts");

The problem is that I have an import in my deviceService.

When I run my test, I have an error from my file device.service.ts:

import { Injectable } from '@nestjs/common';
       ^

SyntaxError: Unexpected token {

For information, I try in my test to create my service with a stub like this:

const deviceRepository = typeorm.getRepository(Device);

const stub = sinon.stub(deviceRepository, "create").returns(stubValue);
const DeviceServiceStubbed = new DeviceService(deviceRepository);

Stack used: nestJs / Chai / Sinon / Typeorm

Thank you!


Solution

  • The problem is that my mocha call was wrong. I changed "test": "mocha" to "test": "mocha --require ts-node/register in my package.json and now it works fine