Replies: 2 comments
-
@sheremet-va Any idea why the example on the doc doesn't work? Is that expected? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Thanks to @sheremet-va for the help on Discord and realised the main reason I wasn't able to get it working was due to I assumed Vitest's automocking works exactly the same as Jest but I was wrong. At this point of time, when automock a class with Vitest, it doesn't automock the class prototype which we will need to do it manually. Actual Codehandler.js export function success(data) {}
export function failure(data) {} getTodos.js import { failure, success } from './handler.js';
import { Client } from 'pg';
export default async (event, context) => {
const client = new Client({});
await client.connect();
try {
const result = await client.query('SELECT * FROM todos;');
client.end();
return success({
message: `${result.rowCount} item(s) returned`,
data: result.rows,
status: true,
});
} catch (e) {
client.end();
return failure({ message: e, status: false });
}
}; Test CodeJest import { Client } from 'pg';
import getTodos from './getTodos.js';
jest.mock('pg');
jest.mock('./handler.js');
describe('get a list of todo items', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should return items successfully', async () => {
await getTodos();
expect(Client.prototype.connect).toHaveBeenCalledTimes(1);
expect(Client.prototype.query).toHaveBeenCalledWith('SELECT * FROM todos;');
expect(Client.prototype.end).toHaveBeenCalledTimes(2);
});
}); Vitest import { afterEach, describe, expect, it, vi } from 'vitest';
import { Client } from 'pg';
import getTodos from './getTodos.js';
vi.mock('pg', () => {
const Client = vi.fn();
Client.prototype.connect = vi.fn();
Client.prototype.end = vi.fn();
Client.prototype.query = vi.fn();
return { Client };
});
vi.mock('./handler.js', () => {
return {
success: vi.fn(),
failure: vi.fn(),
};
});
describe('get a list of todo items', () => {
afterEach(() => {
vi.clearAllMocks();
});
it('should return items successfully', async () => {
await getTodos();
expect(Client.prototype.connect).toBeCalledTimes(1);
expect(Client.prototype.query).toBeCalledWith('SELECT * FROM todos;');
expect(Client.prototype.end).toBeCalledTimes(2);
});
}); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi guys, I'm trying to migrate my Jest tests over to Vitest, but somehow bumped into an issue where the mocked instance isn't being used in the actual code which leads to the expect().toBeCalledWith() failure. Is there any configuration I'm missing out? Thanks.
https://stackblitz.com/edit/vitest-dev-vitest-rmsdsh?file=src/getTodos.spec.js
Note: The above is an example from here.
Beta Was this translation helpful? Give feedback.
All reactions