Search code examples
javascriptjestjsts-jest

Why are the mocks for the httpService not changing their behavior in the second block, even when different constants are used for mocking?


I'm new to Jest and I'm encountering an issue with mocking the httpService in multiple it() blocks. After mocking the httpService in the first it() block, the second it() block fails to pass. I've attempted to use spyOn, but it didn't work well with AxiosResponse, and even after fixing it, the second block still fails. I also tried clearAllMocks() and resetAllMocks(), but they didn't resolve the issue. Can someone please help me understand and resolve this problem?

  beforeEach(async () => {
    module = await Test.createTestingModule({
      providers: [CPDCService, ...providersMock]
    }).compile();

    service = module.get<CPDCService>(CPDCService);
    jest.resetAllMocks();
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('submit', () => {
    it('should throw BadRequestException when Recaptcha token is invalid', async () => {
      const httpService = module.get<HttpService>(HttpService);
      const cpdcData: CPDCDto = {
        formData: {
          recaptchaToken: 'mockRecaptchaToken',
          email: 'test@example.com'
        },
        campaignId: 'mockCampaignId',
        bountyId: 'mockBountyId',
        formId: 'mockFormId',
        referrer: 'google.com',
        deviceId: 'mockDeviceId'
      };

      // Mock the response from the recaptcha verification
      const recaptchaResponse = {
        data: {
          success: false
        }
      };
      // Create a spy on the `post` method of `httpService`
      const mockObservable = {
        toPromise: () => Promise.resolve(recaptchaResponse)
      };
      httpService.post = jest.fn().mockImplementation(() => mockObservable);

      await expect(service.submit(cpdcData, true, undefined, 'en')).rejects.toThrow(
        BadRequestException
      );
    });
    it('should throw NotFoundException when campaign is not found', async () => {
      const httpService = module.get<HttpService>(HttpService);
      const cpdcData: CPDCDto = {
        formData: {
          recaptchaToken: 'mockRecaptchaToken',
          email: 'test@example.com'
        },
        campaignId: 'mockCampaignId',
        bountyId: 'mockBountyId',
        formId: 'mockFormId',
        referrer: 'google.com',
        deviceId: 'mockDeviceId'
      };

      // Mock the response from the recaptcha verification
      const recaptchaResponse = {
        data: {
          success: true
        }
      };
      // Create a spy on the `post` method of `httpService`
      const mockObservable = {
        toPromise: () => Promise.resolve(recaptchaResponse)
      };
      httpService.post = jest.fn().mockImplementation(() => mockObservable);

      await expect(service.submit(cpdcData, true, undefined, 'en')).rejects.toThrow(
        NotFoundException
      );
    });
  });
});

Solution

  •   describe('submit', () => {
        it('should throw BadRequestException when Recaptcha token is invalid', async () => {
          const recaptchaResponse = {
            data: {
              success: false
            }
          };
    
          // Create a spy on the `post` method of `httpService` and mock the implementation
          const promiseMock = jest.fn().mockReturnValueOnce(Promise.resolve(recaptchaResponse));
          jest.spyOn(httpService, 'post').mockReturnValue({ toPromise: promiseMock } as any);
    
          await expect(service.submit(cpdcData, true, undefined, 'en')).rejects.toThrow(
            BadRequestException
          );
        });
        it('should throw NotFoundException when campaign is not found', async () => {
          const recaptchaResponse = {
            data: {
              success: true
            }
          };
    
          // Create a spy on the `post` method of `httpService` and mock the implementation
          const promiseMock = jest.fn().mockReturnValueOnce(Promise.resolve(recaptchaResponse));
          jest.spyOn(httpService, 'post').mockReturnValue({ toPromise: promiseMock } as any);
    
          await expect(service.submit(cpdcData, true, undefined, 'en')).rejects.toThrow(
            NotFoundException
          );
        });
      });
    

    this worked!