Unable to conduct end-to-end testing as Nestjs fails to resolve dependencies

I encountered the following error :

Nest is unable to resolve dependencies of the ParametrageRepository (?). Please ensure that the argument DataSource at index [0] is available in the TypeOrmModule context.

This is my test code :

describe("ParametrageController (e2e)", () => {
    let parametrage: INestApplication;

    beforeEach(async () => {
        const moduleFixture: TestingModule = await Test.createTestingModule({
            imports: [ParametrageModule],
        }).compile();

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

    it("/ (POST)", () =>
        request(parametrage.getHttpServer())
            .post("/parametrage")
            .send({
                libelle: "GROUPE_TYPE",
                liste: ["TEAM", "SERVICE", "ORGANISATION"],
            })
            .expect(201));
});

This is my module code:

@Module({
    imports: [TypeOrmModule.forFeature([Parametrage])],
    exports: [TypeOrmModule],
    controllers: [ParametrageController],
    providers: [ParametrageService, ParametrageRepository, ParametrageActions, Logger],
})
export class ParametrageModule {}

I am unsure why I am facing this error even though I followed the Nestjs documentation. It's possible that I missed a crucial step or overlooked something while setting up my providers with parameters in their constructors :

This is my ParametrageRepository provider :

@Injectable()
export class ParametrageRepository
    extends RepositoryStarter<Parametrage, IParametrageListFilter>
    implements IParametrageRepository
{
    constructor(@InjectDataSource() datasource: DataSource) {
        super(datasource.getRepository(Parametrage));
    }

I attempted to introduce provider injection :

const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [ParametrageModule],
**      providers: [
                 { provide: ParametrageActions, useValue: ParametrageActions },
                 { provide: ParametrageRepository, useValue: ParametrageRepository },
                         { provide: Logger, useValue: Logger ,
                ],**
}).compile();

However, the error persists and remains unsolved

Appreciate any help in advance

Answer №1

An error message is indicating that the DataSource cannot be resolved, which suggests that there are extra dependencies in the module that need to be provided or mocked.

There are a few ways to address this issue:

  1. Utilize a testing database and modify the code as follows:
const moduleFixture: TestingModule = await Test.createTestingModule({
  imports: [TypeOrm.forRoot(databaseConfig), ParametrageModule],
}).compile();

This will allow you to work with the Repositories by injecting the DataSource.

  1. You can create a mock implementation of the DataSource like this:
const moduleFixture: TestingModule = await Test.createTestingModule({
  imports: [ParametrageModule],
  provide: [{ provide: DataSource, useFactory: dataSourceMockFactory }]
}).compile();

In this case, dataSourceMockFactory is a function that should return an object with the necessary methods.

  1. If preferred, you can declare the module inline and provide a mock for the repository:
const moduleFixture: TestingModule = await Test.createTestingModule({
  controllers: [ParametrageController],
  providers: [ParametrageService, { provide: ParametrageRepository, useFactory: parametrageRepositoryMockFactory }, ParametrageActions, Logger]

For the parametrageRepositoryMockFactory, only mock the methods that are required for the test scenario, such as findAll and create.

Starting with the first approach (testing DB) is recommended as it provides real results rather than just mocks, making it more reliable. Make sure not to use the production DB for tests to avoid data manipulation.

The second and third approaches are suitable for unit tests but may not be ideal in this situation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter. Instead of manually modifying each router-link and router.push, I am looking for a solution using rout ...

A guide on transferring received data from dataService within the parent component to the child component in Angular2

Within the context of my application, there exists a parent component named app-parent and a child component called app-child. In app-parent, I retrieve data from a DataService. @Component({ selector: 'app-parent', providers: [DataService] ...

Using the power of jQuery to load Ajax content, unfortunately, the content remains

Hey there, I'm currently working with an HTML file that utilizes AJAX to load content from other HTML files on the same server. However, for some reason, it's not functioning properly. I'm new to AJAX and I'm not sure what could be caus ...

A guide on implementing Angular ngbPopover within a CellRenderer for displaying in an ag-grid cell

I successfully set up an Angular Application and decided to utilize ag-grid community as a key component for displaying data from a backend API in tables, using fontawesome icons to enhance readability. While everything looks fine and my application is fu ...

`There is a lack of props validation in the react/prop-types``

As I set up my Next-React app on Netlify, I encountered an error in the deploy log: Netlify deploy log indicates: "Error: 'Component' is missing in props validation", "Error: 'pageProps' is missing in props validation" within my ./page ...

The JSON data response is not being properly displayed on the div element

I am having trouble with the success function in my ajax call. The data is processed correctly in the view and the ajax call works fine, but for some reason, the data is not getting appended to the div. Here is my jQuery: $(document).ready(function() { ...

How can I connect a custom Web Resource button in Dynamics CRM 2015 to a specific function within a Javascript Library integrated into the form?

I have added a button to the form using the following code: <button type="button" onclick="btnCalculate_onClick();">test</button> Within the form, I have included a function called btnCalculate_onClick() from a Library named dc_btnAutofillAdd ...

How can I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

Tips on incorporating the vue package

I recently started using Vue and decided to incorporate a plugin called vue-toastr. I'm attempting to integrate it with Laravel, which already has Vue set up with the plugin. Unfortunately, I keep encountering an error that says "TypeError: Cannot rea ...

Headers cannot be set after they have already been sent following the establishment of the content-type

Currently, I'm attempting to retrieve an object from my server's API. This particular API presents the object as a stream. To properly handle the MIME type of the object (which typically ends in .jpg or similar), I want to ensure that the conte ...

Discover the process of incorporating two distinct component structures within a single React application

In my React app, I am trying to implement a different navbar for routes that start with "admin". For example: Normal Page: <NormalNavbar/> <NormalHeader/> <NormalBody/> <NormalFooter/> But if it's an admin route, then I want: ...

Saving JSON data into an HTML element using Handlebars templating

Is there a way to save the entire JSON object within an HTML element as a data attribute? let a = {name : "sample", age : "34"} $.find('#someDiv').data('adata', a); Is it possible to achieve the same result using Handlebars when creat ...

Is there a way to enable intellisense in vscode while editing custom CSS within a material-ui component?

Is there a vscode extension recommendation for intellisense to suggest css-in-js for customized material ui components in .tsx files? For example, I want intellisense to suggest 'backgroundColor' when typing. The closest I found is the 'CSS- ...

Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the fiel ...

What is the best way to create a function library that works seamlessly across all of my Vue.js components?

I am currently in the process of developing a financial application using Vue.js and Vuetify. As part of my project, I have created several component files such as Dashboard.vue Cashflow.vue NetWorth.vue stores.js <- Vue Vuex Throughout my development ...

Is it possible to create an observable with RXJS that emits only when the number of items currently emitted by the source observables matches?

I am dealing with two observables, obs1 and obs2, that continuously emit items without completing. I anticipate that both of them will emit the same number of items over time, but I cannot predict which one will emit first. I am in need of an observable th ...

aviary usage resulted in a file_get_contents error

I successfully integrated aviary into my webpage and it's functioning properly. However, I'm encountering an issue with using the file_get_contents command to retrieve the saved image. Here's the aviary code: JS: <!-- Load Feather code ...

incorrect calculation of date difference using momentjs

Currently utilizing countdown.js for a project where I need to add 60 days to a date fetched from the database. Successfully implemented this in the targetDay variable and it's functioning properly. However, when attempting to calculate this date fro ...

Contrasting jquery-1.4.1.min.js and jquery-1.4.1.js

Question: What is the difference between jquery.js and jquery-min.js? When creating a new project in VS2010, two files are included: jquery-1.4.1.js and jquery-1.4.1-min.js. The former has more readable variables and minimal comments. What exactly is ...

Can you explain the significance of this async JavaScript server application error?

While working on a weather app website connected to another site through a server, I encountered an issue with asynchronous JavaScript. Upon running the code, I received an error message stating "uncaught syntax error: unexpected end of input" in the last ...