knee-cola/jest-mock-axios

mockAxios.post not working

Closed this issue · 1 comments

I have following code:

describe('trackConversion', () => {
    it('should be called with following parameters', async () => {
      const experiment = {
        id: '--experiment-id--'
      }
      const variant = new PrizmoVariant(experiment, '--variant-id--')
      variant.baseUrl = process.env.BASE_URL
      variant.collectFeatures = jest.fn(() => ({}))
      const result = await variant.trackConversion({
        probability: 1
      })
      expect(result).toBeEqual({})
      expect(mockAxios.post).toHaveBeenCalledWith(
        `${process.env.BASE_URL}/trackConversion`,
        {
          eid: experiment.id,
          vid: variant.id,
          probability: 1,
          features: {}
        }
      )
    })
  })

And variant.trackConversion code:

  async trackConversion ({ probability }) {
    await axios.post(
      `${this.baseUrl}/trackConversion`,
      {
        eid: this.experiment.id,
        vid: this.id,
        probability,
        features: await this.collectFeatures(),
        ts: new Date()
      },
      { withCredentials: true }
    )
  }

And this test fails with reason Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

This means, execution never reach expect(result).toBeEqual({}) line.

This means jest-mock-axios not working.

You're missing a mockAxios.mockResponse call before the expect(result) statement.