A
A
Artem2018-04-20 14:06:43
Software testing
Artem, 2018-04-20 14:06:43

How to test (or lock) a module when there is an import of constants from external files (NodeJS, ExpressJS, NestJS)?

I'm trying to write an e2e application test on Nest ( https://nestjs.com/ ) - an add-on for ExpressJS.

Here is one of the modules:

import {Module} from '@nestjs/common';
import {DatabaseService} from './database.service';
import {config} from "../configuration";
import {SharedModule} from "../shared/shared.module";

const pgp = require('pg-promise')();
const db = pgp({
    host: config.database.host,
    ...
});

const connectionProvider = { provide: 'DatabaseToken', useValue: db };

@Module({
    components: [DatabaseService, connectionProvider],
    exports: [DatabaseService],
    imports: [SharedModule]
})
export class DatabaseModule {}


This is what the test looks like:
import * as express from 'express';
import * as request from 'supertest';
import { Test } from '@nestjs/testing';
import {AppModule} from "../src/app.module";

describe('Application', () => {
    const server = express();
    
    beforeAll(async () => {
        const module = await Test.createTestingModule({
            imports: [AppModule],
        }).compile();

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

    it(`/GET area`, () => {
        return request(server)
            .get('/area')
            .expect(200)
            .expect({
                data: {}
            });
    });
});


When running the test, an error occurs:
TypeError: Cannot read property 'host' of undefined


I tried to lock the import of the constant:
jest.mock('../configuration', () => ({
            database: {
                host: ''
            },
        }));


But the result is the same. Either I did not write the test correctly, or an error in the architecture.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question