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.