Angular Jest mock post request

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: '[email protected]',
      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' }));

New contributor

CiprianGr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật