Angular Jest mock post request

Discussão em 'Angular' iniciado por CiprianGr, Dezembro 8, 2024.

  1. CiprianGr

    CiprianGr Guest

    First time using jest and I'm having some big problems on mocking a service with a post method request. I think I spend more than 6 hours on this and still can't pass it. I would appreaciate any help. First I'll say about libraries versions. As ChatGpt told, those should be compatible with each other. jest: 29.7.0, jest-preset-angular: 14.4.2, ts-jest: 29.2.5, ts-node: 10.9.2, typescript: 5.5.2, angular/cli: 18.2.11, angular/core: 18.2.0. Method which I want to test is this one, from Registration component:

    submitForm(event: Event): void {
    event.preventDefault();
    if (!this.contactFormGroup.valid) {
    this.errorForm = true;
    return;
    }

    this.errorForm = false;
    const registerSub = this.coreService.registerUser(this.contactFormGroup.value).subscribe({
    next: (response) => {
    alert(response.message);
    this.contactFormGroup.reset();
    },
    error: () => {
    alert('There was an error while submitting the form. Please try again');
    this.contactFormGroup.reset();
    },
    });
    this.subscriptions.add(registerSub)
    }
    registerUser from coreserver:
    registerUser(userData: userData): Observable<RequestType> {
    const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    });

    return this.httpClient.post<RequestType>('http://localhost:3000/register', userData, { headers});
    }



    What i tried:

    describe('RegistrationComponent', () => {
    let component: RegistrationComponent;
    let fixture: ComponentFixture<RegistrationComponent>;
    let mockCoreService: CoreService;

    beforeEach(async () => {
    mockCoreService = MockService(CoreService);

    await TestBed.configureTestingModule({
    imports: [
    ReactiveFormsModule,
    CommonModule,
    HttpClientTestingModule
    ],
    providers: [
    { provide: CoreService, useValue: mockCoreService }
    ]
    }).compileComponents();

    fixture = TestBed.createComponent(RegistrationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    });

    it('should submit form successfully', fakeAsync(() => {
    const mockResponse = { message: 'Registration successful' };
    jest.spyOn(mockCoreService, 'registerUser').mockReturnValue(of({ message: 'Registration successful!', status: 'success' }));
    jest.spyOn(window, 'alert');

    component.contactFormGroup.setValue({
    username: 'testuser',
    fullname: 'Test User',
    email: 'test@test.com',
    password: 'TestPass123!'
    });

    const event = new Event('submit');
    event.preventDefault();
    component.submitForm(event);
    tick(100);

    expect(mockCoreService.registerUser).toHaveBeenCalled();
    expect(window.alert).toHaveBeenCalledWith(mockResponse.message);
    }));


    The problem is here: expect(mockCoreService.registerUser).toHaveBeenCalled(); I just can t mock this line and the method is not mocked correctly. this is what I think and what i tested even with console logs inside next observable and error in .ts file.

    error by npm run test: expect(jest.fn()).toHaveBeenCalled() Expected number of calls: >= 1 Received number of calls: 0

    If you have any idea how to solve this, I would appreciate.

    I also tried with ng-mock and also something like:

    let coreServiceSpy: jest.Mocked<CoreService>;


    beforeEach(async () => {
    coreServiceSpy = {
    registerUser: jest.fn().mockReturnValue(of({ message: 'Registration successful!', status: 'success' })),
    } as any;


    and in test: coreServiceSpy.registerUser.mockReturnValue(of({ message: 'Registration successful!', status: 'success' }));

    Continue reading...

Compartilhe esta Página