The exportAs attribute is not specified as "ngForm" for any directive

Encountered an error while attempting to test the LoginComponent

PhantomJS 2.1.1 (Linux 0.0.0): Executed 3 of 55 (1 FAILED) (0 secs / 0.307 secs)
PhantomJS 2.1.1 (Linux 0.0.0) LoginComponent should create FAILED
Failed: Uncaught (in promise): Error: Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("iv class="col-md-4 col-sm-6 col-md-offset-4 col-sm-offset-3">
          <form (ngSubmit)="login(f)" [ERROR ->]#f="ngForm">
            <div class="card card-login">
              <div class="card-header text-cen"): LoginComponent@5:38

A snippet from my component code,

login.component.ts

export class LoginComponent {

  isBusy: boolean = false;
  user: User;

  constructor(
    private router: Router,
    private notificationService: NotificationService,
    private authService: AuthenticationService,
    private sessionService: SessionService,
  ) { }
  ....
}

The corresponding spec file for the component,

login.component.spec.ts

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    let routerStub = new RouterStub();

    TestBed.configureTestingModule({
      imports: [HttpModule],
      declarations: [,
        LoginComponent
      ],
      providers: [{
        provide: Http, useFactory: (backend, options) => {
          return new Http(backend, options);
        },
        deps: [MockBackend, BaseRequestOptions]
      },
      { provide: Router, useClass: class { navigate = jasmine.createSpy("navigate"); } },
        MockBackend,
        BaseRequestOptions,
        AuthenticationService,
        SessionService,
        NotificationService
      ],
      schemas: [NO_ERRORS_SCHEMA],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

It seems like there might be an issue with creating a mock component using the given providers and declarations. As mentioned by others in this discussion, I have already included FormsModule within the @NgModule decorator.

Answer №1

Uncertain about the placement of the @NgModule decorator, but I believe it should be included in

 TestBed.configureTestingModule({
      imports: [HttpModule, FormsModule],

Answer №2

Dealing with a similar issue, I managed to resolve it by including FormsModule in BOTH app.module.ts AND the sub-module where the component is located, which for me was core.module.ts.

Adhering to the Angular style guide, I placed the login component within the core module, resulting in this folder structure: app/src/core/login/login.component.ts

In my case, there was no need to import ReactiveFormsModule as some recommendations had suggested.

Answer №3

The accepted answer may not be up to date since the HttpModule is now marked as deprecated. A better option would be to utilize HttpClientTestingModule instead:

TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, FormsModule],

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

Updating label values to default in JavaScript/jQuery

I need to utilize jQuery/js for the following tasks: Extract label values from form inputs Insert those labels as input values in the corresponding fields Conceal the labels It's a simple task. Instead of manually entering each label like this: $( ...

Creating an import map using jspm2 can be done by following these steps

Currently, my goal is to utilize JSPM module loader to import javascript packages from npm instead of CDN and employ an offline package loader. Now, the next step involves incorporating an importmap script in order to successfully import modules like rea ...

The error message "Failed to load the default credentials in Firebase" occurs sporadically. Approximately 50% of the time, the app functions properly, while the other 50% of the time, this specific

Occasionally in my firebase functions log, I encounter an error message stating: "Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information." This error appears randomly withi ...

Inaccurate recommendations for type safety in function overloading

The TypeScript compiler is not providing accurate suggestions for the config parameter when calling the fooBar function with the 'view_product' type. Although it correctly identifies errors when an incorrect key is provided, it does not enforce t ...

Adjust the background of the input range style prior to the thumb icon

Is there a way to style the bar before the thumb with a different color on a range input? I have been searching for a solution without much success. This is the desired look: Unfortunately, Chrome no longer supports input[type='range']::-webkit- ...

"Exploring the world of Skeletal Animation with Three.js

I'm struggling with animating in Three.js and I can't figure out if the issue lies in my code or my blender file. Below is the code that I'm using to load and animate the model. Please review it and let me know if you spot any errors. load ...

Having trouble interacting with Bootstrap modal dialog when fullPage.js is active

Whenever I attempt to click on the button, a Bootstrap modal dialog box appears but remains unresponsive no matter what I try. My project utilizes both Bootstrap and fullPage.js http://codepen.io/anon/pen/obEOzO <body> <div id="fullpage"> &l ...

Minimum number of coins required for a specific amount

I need assistance creating a JavaScript/jQuery function to determine the minimum number of coins required to reach a specified total amount. Here is an array object containing different coin values: var coins = [ { pennies: 200, prin ...

Resolving the problem of Turkish uppercase dotted i when using the capitalization pipe in Angular 2

I have created a custom capitalization pipe that successfully capitalizes almost all characters, including converting the Turkish 'ı' character into 'I'. However, I am facing an issue where the 'i' character is also being con ...

In the Safari browser, an error occurred when trying to locate the variable Tmpo, which is a plain JavaScript class

I created a small Angular application that utilizes a basic JavaScript class located in my assets/js directory. Everything functions flawlessly in my local environment when using ng-serve. However, upon building and deploying the app (ng build --prod), I e ...

Passing PHP values to JavaScript and then to AJAX requires using the appropriate syntax and techniques for

Currently, I am populating a table with data retrieved from my database. Here is a snippet of the code: <?php //mysqli_num_rows function while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point echo "<tr><t ...

Using ReactJS to incorporate events with an external DOM element

I am using ReactJS version 16.13.1 and I have the need to display an external DOM element along with its events. Let's consider having a <button type="button" id="testBtnSiri" onclick="alert('Functionality exists');">Testbutton Sir ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...

The ng-repeat function is currently disabled and not displaying any data from the JSON object

I am currently facing an issue where the ng-repeat Directive in my code is getting commented out and not displaying the results of the JSON object. I have verified that the object is being properly passed to "this.paises2" using the toSource() method, and ...

How can Vue.js implement a satisfactory method for synchronizing computed values with asynchronous data?

Imagine retrieving a list of products from the state manager in your Vue.js component, where a computed property is then used to process this list for display on the DOM. <template> <span>{{ computedProducts }}</span> </template> ...

Error: JSON parsing encountered an unexpected character "D" at position 1

When I call a python script as a child process from my node.js app to extract data from an uploaded file, I encounter the error 'UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token D in JSON at position 1" when uploading the file thro ...

How can I design an avatar image within a button similar to Facebook's style?

I'm currently working on a project that involves adding an avatar and a dropdown menu for account settings to my navigation bar. I've already created the dropdown, but I'm having trouble styling the avatar within the button. The button is ta ...

I would appreciate it if someone could clarify how the rendering process occurs in React in this specific scenario

let visitor = 0; function Mug({name}) { visitor = visitor + 1; console.log(name, visitor); return <h2>Coffee mug for visitor #{visitor}</h2>; } return ( <> <Mug name={"A"}/> <Mug name={"B&qu ...

Leveraging default values in generic implementations

Imagine a scenario where the following code is present: type QueryResult<ResultType = string, ErrorType = string> = { result: ResultType, } | { errors: ErrorType, } So, if I want to initialize my result, I can proceed like this: const myResult: ...

AngularJS constants are values that can be accessed and

Is it feasible to inject one constant into another constant using AngularJS? For example: var app = angular.module('myApp'); app.constant('foo', { message: "Hello" } ); app.constant('bar', ['foo', function(foo) ...