NestJS: e2e testing using an axios-based client is not working as expected

Viewed 366

I have a NestJS application that exposes some endpoints, and I have written a client application that I plan on releasing as an NPM package to work with the nest server. I am attempting to write end-to-end tests that start the nest server, connect it to a test database in a local docker container, and test it using the client. Here are some snippets of what I'm attempting to do:

Controller:

@Controller('/api/v1/messages')
export class MessagesController {

    constructor(
        private messagesService: MessagesService
    ) {}

    @Get()
    @UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
    private findAll(
        @Query() searchCriteria: MessageSearchDto
    ): Promise<MessageDto[]> {
        if (Object.keys(searchCriteria).length > 0) 
            return this.messagesService.search(searchCriteria);
        return this.messagesService.findAll();
    }
}

Client:

const http = require('axios');
const dotenv = require('dotenv');

dotenv.config();

export class MessageClient {

    public baseUri: string = process.env.MessageClientTarget ?? './';

    constructor() {}

    public async findAll() {
        return await http.get(this.baseTarget());
    }

    private baseTarget() {
        return `${this.baseUri}/api/v1/messages`;
    }
}

e2e Test:

describe('MessageController (e2e)', () => {
    let app: INestApplication;
    let client: MessageClient = new MessageClient();

    beforeAll(async () => {
        let moduleFixture: TestingModule = await Test.createTestingModule({
        imports: [AppModule, MessagesModule],
        }).compile();

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

    afterAll(async () => {
        await app.close();
    });

    it('/ (GET)', async done => {
        const { data: messages } = await client.findAll()
        expect(messages).toEqual([]);    
        done();
    });
});

And .env:

MessageClientTarget=http://localhost:3000

When I attempt to run this, I get the following error: "connect ECONNREFUSED 127.0.0.1:3000"

From what I understand, this is because the createNestApplication method doesn't actually start a server but instead creates a mocked version of the application.

My question is how can I work with INestApplication or TestingModule in order to start the application or what other way do I have to programmatically start a NestJS application. It is important to me that I perform the e2e testing with the Axios based client rather than supertest as a way of testing both the client and the server.

I have verified that the server is supposed to start on port 3000 locally, and I have verified that the client has the correct baseUri set. The address used by the client during testing is: http://localhost:3000/api/v1/messages and was verified by outputting the value to the console during the test. Also, only the database currently lives in a docker container and I have that running correctly. The whole application works perfectly when ran locally and it is only in the test that it is failing.

1 Answers

Please make sure that the test environment where you are running tests is set to node. Add testEnvironemnt:'node' jest parameter in your jest configuration file.

You can run e2e tests with any client of your choice regardless of whether or not you are running a nestjs testing module or the actual nestjs application instance. I personally use testing module as it makes very easy to mock any third-party dependencies of the application when testing it (that is the main purpose of the testing module, providing an elegant manner to substitute or mock any component that you may want to).

Related