جاوااسکریپت - عدم توانایی اجرای تست Vitest با خطا: "Vitest در طول اجرای تست ۱ خطای مدیریتنشده را ثبت کرد"


من یک تابع دارم که سعی دارم از طریق Vitest آن را تست کنم.

این تابع من است (تابع صادر شده را تست میکنم):

import os from 'node:os';

import { AI_COMMIT_IGNORED_FILES } from '../constants/ai-commit';
import { asyncExec } from './os';

/**
 * The function returns array of files paths that are in staged mode
 * @returns array of files paths in staged mode
 */
const getStagedFiles = async () => {
    const gitCommand = 'git diff --name-only --cached --relative .';
    const { stdout: filesOutput, stderr } = await asyncExec(gitCommand);

    if (stderr) {
        throw new Error(stderr);
    }

    const filesList = filesOutput.split(os.EOL).filter(Boolean);

    return filesList;
};


/**
 * The function returns the "git diff" command output for relevant staged files in the commit
 * @returns "git diff" output as a string
 */
export const getStagedFilesDiff = async () => {
    const stagedFiles = await getStagedFiles();
    const filteredFiles = stagedFiles.filter((file) => !AI_COMMIT_IGNORED_FILES.includes(file));

    const gitCommand = `git diff --staged -- ${filteredFiles.join(' ')}`;
    const { stdout: diffOutput, stderr } = await asyncExec(gitCommand);

    if (stderr) {
        throw new Error(stderr);
    }

    return diffOutput;
};

و این تابع asyncExec است:

import { exec } from 'node:child_process';
import util from 'node:util';

export const asyncExec = util.promisify(exec);

من آزمایش زیر را نوشتم:

import { describe, it, expect, vi } from 'vitest';

import { asyncExec } from '@/utils/os';
import { getStagedFilesDiff } from '@/utils/git-info';

vi.mock('@/utils/os');

describe('[utils/git-info]', () => {
    describe('getStagedFilesDiff()', () => {
        it('should throw an error when "asyncExec" throws', () => {
            vi.mocked(asyncExec).mockRejectedValueOnce(undefined);

            expect(() => getStagedFilesDiff()).toThrowError();
        });
    });
});

اما سپس با خطا مواجه شدم:

Vitest caught 1 unhandled error during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.


This error originated in "tests/utils/git-info.spec.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
 ELIFECYCLE  Test failed. See above for more details.

من این را دنبال کردهام: https://vitest.dev/api/expect.html#tothrowerror

پس نمیفهمم چرا کار نمیکند..؟


من همچنین امتحان کردهام:

        it('should throw an error when "asyncExec" throws', async () => {
            vi.mocked(asyncExec).mockRejectedValueOnce(undefined);

            await expect(() => getStagedFilesDiff()).rejects.toThrowError(undefined);
        });

خطا به این صورت است:

AssertionError: expected [Function] to throw an error

سپس تابع getStagedFilesDiff را با try {} catch {} به صورت زیر پیچیدم:

export const getStagedFilesDiff = async () => {
    try {
        const stagedFiles = await getStagedFiles();
        const filteredFiles = stagedFiles.filter((file) => !AI_COMMIT_IGNORED_FILES.includes(file));

        if (filteredFiles.length === 0) {
            return null;
        }

        const gitCommand = `git diff --staged -- ${filteredFiles.join(' ')}`;
        const { stdout: diffOutput, stderr } = await asyncExec(gitCommand);

        if (stderr) {
            throw new Error(`Failed to get "git diff" output of staged files with error:\n${stderr}`);
        }

        return diffOutput;
    } catch {
        throw new Error();
    }
};

سپس تست با موفقیت انجام شد.

پاسخ شماره ۱

من توانستم این مشکل را با انجام دادن موارد زیر حل کنم:

        it('should throw an error when "asyncExec" throws', async () => {
            vi.mocked(asyncExec).mockRejectedValueOnce(new Error());

            await expect(() => getStagedFilesDiff()).rejects.toThrowError();
        });