Currently experimenting with nestjs and jest in a personal project, I've encountered some challenges while trying to properly utilize the expect().toHaveReturnedWith()
methods.
I wonder if the issue lies in how I set the resolved value:
jest.spyOn(subscriptionsHistoryRepository, 'findAll').mockResolvedValue([mockRecords, 2])
? Although upon debugging the test, it seems that .findAll()
does return the mockRecords as expected.
Here is the snippet of code I am working on:
describe('SubscriptionsModule', () => {
describe('GetSubscriptionHistoryService', () => {
let service: GetSubscriptionHistoryService;
let subscriptionsHistoryRepository: SubscriptionsHistoryRepository;
beforeAll(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
providers: [
GetSubscriptionHistoryService,
{
provide: SubscriptionsHistoryRepository,
useValue: {
findAll: jest.fn(),
},
},
],
}).compile();
service = moduleRef.get<GetSubscriptionHistoryService>(GetSubscriptionHistoryService);
subscriptionsHistoryRepository = moduleRef.get<SubscriptionsHistoryRepository>(
SubscriptionsHistoryRepository,
);
});
afterEach(() => {
jest.resetAllMocks();
});
it('Should have all class instances defined', () => {
expect(service).toBeDefined();
expect(subscriptionsHistoryRepository).toBeDefined();
});
it("Should return the subscription's status history", async () => {
jest.spyOn(subscriptionsHistoryRepository, 'findAll').mockResolvedValue([mockRecords, 2]);
await service.execute(CUSTOMER_ID, SUBSCRIPTION_ID, 1);
expect(subscriptionsHistoryRepository.findAll).toHaveBeenCalledTimes(1);
expect(subscriptionsHistoryRepository.findAll).toHaveBeenCalledWith({
where: {
customerId: CUSTOMER_ID,
subscriptionId: SUBSCRIPTION_ID,
},
take: 5,
skip: 0,
order: {
createdAt: 'DESC',
},
});
expect(subscriptionsHistoryRepository.findAll).toHaveReturnedWith([mockRecords, 2]);
});
});
});
Test Results:
expect(jest.fn()).toHaveReturnedWith(expected)
Expected: [[{"createdAt": 2023-11-30T02:02:51.982Z, "customerId": "f1e8fc48-4780-45e4-858b-9e15b3382db5", "deletedAt": null, "extProviderStatus": "trialing", "id": "2e4c42b1-3d46-4438-bc68-64de46aa16d0", "status": "started", "subscriptionId": "2e4c42b1-3d46-4438-bc68-64de46aa16d5", "updatedAt": 2023-11-30T02:02:51.982Z}, {"createdAt": 2023-11-30T02:02:51.982Z, "customerId": "f1e8fc48-4780-45e4-858b-9e15b3382db5", "deletedAt": null, "extProviderStatus": "active", "id": "2e4c42b1-3d46-4438-bc68-64de46aa16d1", "status": "active", "subscriptionId": "2e4c42b1-3d46-4438-bc68-64de46aa16d5", "updatedAt": 2023-11-30T02:02:51.982Z}], 2]
Received: {}
All other assertions seem to be functioning correctly, but the line
expect(subscriptionsHistoryRepository.findAll).toHaveReturnedWith([mockRecords, 2])
returns an empty object {}
.
Upon debugging the test run, it appears that spyOn.mockResolved worked fine. I'm uncertain about what could be missing or why this particular assertion is failing.