As @Diaboloxx mentioned you should be mocking out your HttpService
via the providers
setup in your tests.
Ideally anything that you are dependency injecting into your constructor you should be providing and mocking out. That way your tests are isolated to the given file, and in this case to help prevent making real requests.
I like to use mockDeep
from the library: jest-mock-extended
to handle mocking on the providers to see what has been called on them, as well as to mock returned values. It's also nice because mockDeep
will enforce type safety to validate that you're mocking valid return data.
Side Note: it is good practice to test that your dependencies are being called with what you expect.
import { HttpService } from '@nestjs/axios'
import { Test, TestingModule } from '@nestjs/testing'
import { mockDeep } from 'jest-mock-extended'
import { of } from 'rxjs'
import { AxiosResponse } from 'axios'
import { MyService } from '@/services/my.service'
describe('MyService', () => {
let myService: MyService
const httpService = mockDeep<HttpService>()
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [myService],
providers: [
{
provide: HttpService,
useValue: httpService,
},
],
}).compile()
myService = app.get<MyService>(MyService)
})
describe('#myMethod', () => {
const response: AxiosResponse<unknown, any> = {
data: { hello: 'world' },
headers: {},
config: { url: 'http://localhost:3000/mockUrl' },
status: 200,
statusText: 'OK',
}
beforeEach(() => {
httpService.post.mockReturnValue(of(response))
})
it('should return "Hello World!"', async () => {
const result = await myService.myMethod({ code: 'value' })
expect(result).toEqual({ hello: 'world' })
})
it('calls httpService.post with the correct params', async () => {
await myService.myMethod({ code: 'value' })
expect(httpService.post).toHaveBeenLastCalledWith(
'someBaseUrl/param1/param2',
{ body: 'body' },
expect.objectContaining({
headers: {
header: 'header',
},
}),
)
})
})
})