yarn-spinner-loader/tests/plugins/webpack.test.ts

99 lines
3.1 KiB
TypeScript

import { describe, it, expect, vi } from 'vitest';
import { YarnSpinnerWebpackLoader } from '../../src/plugins/webpack';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
describe('YarnSpinnerWebpackLoader', () => {
// Fixtures are in tests/fixtures/, not tests/plugins/fixtures/
const projectPath = resolve(__dirname, '../fixtures/simple/.yarnproject');
it('should be a function', () => {
expect(typeof YarnSpinnerWebpackLoader).toBe('function');
});
it('should load .yarnproject files and return exported JSON', function () {
const mockContext = {
getOptions: vi.fn().mockReturnValue({}),
resourcePath: projectPath,
emitError: vi.fn(),
};
const result = YarnSpinnerWebpackLoader.call(mockContext, '');
expect(result).toBeDefined();
expect(typeof result).toBe('string');
expect(result).toContain('export default');
expect(result).toContain('project');
expect(result).toContain('program');
// Ensure no errors were emitted
expect(mockContext.emitError).not.toHaveBeenCalled();
});
it('should pass loadOptions to loadYarnProjectSync', function () {
const mockContext = {
getOptions: vi.fn().mockReturnValue({
loadOptions: {
baseDir: resolve(__dirname, 'fixtures/simple'),
},
}),
resourcePath: projectPath,
emitError: vi.fn(),
};
const result = YarnSpinnerWebpackLoader.call(mockContext, '');
expect(result).toContain('export default');
expect(mockContext.emitError).not.toHaveBeenCalled();
});
it('should handle errors by calling emitError', function () {
const mockContext = {
getOptions: vi.fn().mockReturnValue({}),
resourcePath: 'nonexistent/.yarnproject',
emitError: vi.fn(),
};
const originalSource = '// original source';
const result = YarnSpinnerWebpackLoader.call(mockContext, originalSource);
expect(mockContext.emitError).toHaveBeenCalled();
expect(mockContext.emitError).toHaveBeenCalledWith(expect.any(Error));
// Should return original source on error
expect(result).toBe(originalSource);
});
it('should return original source on error', function () {
const originalSource = '// original source';
const mockContext = {
getOptions: vi.fn().mockReturnValue({}),
resourcePath: 'nonexistent/.yarnproject',
emitError: vi.fn(),
};
const result = YarnSpinnerWebpackLoader.call(mockContext, originalSource);
expect(result).toBe(originalSource);
});
it('should handle non-Error objects in error handling', function () {
const mockContext = {
getOptions: vi.fn().mockReturnValue({}),
resourcePath: 'nonexistent/.yarnproject',
emitError: vi.fn(),
};
YarnSpinnerWebpackLoader.call(mockContext, '');
expect(mockContext.emitError).toHaveBeenCalled();
const emittedError = mockContext.emitError.mock.calls[0][0];
expect(emittedError).toBeInstanceOf(Error);
});
it('should have a default export', () => {
// Import using ESM to check default export
expect(YarnSpinnerWebpackLoader).toBeDefined();
});
});