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

105 lines
3.0 KiB
TypeScript

import { describe, it, expect, vi } from 'vitest';
import { yarnSpinnerRollup } from '../../src/plugins/rollup';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
describe('yarnSpinnerRollup', () => {
// Fixtures are in tests/fixtures/, not tests/plugins/fixtures/
const projectPath = resolve(__dirname, '../fixtures/simple/.yarnproject');
it('should return a Rollup plugin with correct name', () => {
const plugin = yarnSpinnerRollup();
expect(plugin.name).toBe('yarn-spinner-loader');
});
it('should have a load function', () => {
const plugin = yarnSpinnerRollup();
expect(plugin.load).toBeDefined();
expect(typeof plugin.load).toBe('function');
});
it('should load .yarnproject files and return exported code', async () => {
const plugin = yarnSpinnerRollup();
const loadFn = plugin.load as Function;
const mockContext = {
error: vi.fn(),
};
const result = await loadFn.call(mockContext, projectPath);
// If error was called, the file wasn't found or was invalid
if (mockContext.error.mock.calls.length > 0) {
throw new Error(mockContext.error.mock.calls[0][0]);
}
expect(result).toBeDefined();
expect(typeof result).toBe('string');
expect(result).toContain('export default');
expect(result).toContain('project');
expect(result).toContain('program');
});
it('should return null for non-.yarnproject files', async () => {
const plugin = yarnSpinnerRollup();
const loadFn = plugin.load as Function;
const result = await loadFn.call({}, 'some-file.ts');
expect(result).toBeNull();
});
it('should handle errors by calling this.error', async () => {
const plugin = yarnSpinnerRollup();
const loadFn = plugin.load as Function;
const mockThis = {
error: vi.fn(),
};
await loadFn.call(mockThis, 'nonexistent/.yarnproject');
expect(mockThis.error).toHaveBeenCalled();
});
it('should accept loadOptions and pass them to loadYarnProject', async () => {
const plugin = yarnSpinnerRollup({
loadOptions: {
baseDir: resolve(__dirname, '../fixtures/simple'),
},
});
const loadFn = plugin.load as Function;
const mockContext = {
error: vi.fn(),
};
const result = await loadFn.call(mockContext, projectPath);
expect(mockContext.error).not.toHaveBeenCalled();
expect(result).toBeDefined();
expect(typeof result).toBe('string');
expect(result).toContain('export default');
});
it('should correctly serialize the result as JSON', async () => {
const plugin = yarnSpinnerRollup();
const loadFn = plugin.load as Function;
const mockContext = {
error: vi.fn(),
};
const result = await loadFn.call(mockContext, projectPath);
if (mockContext.error.mock.calls.length > 0) {
throw new Error(mockContext.error.mock.calls[0][0]);
}
// The result should be valid JavaScript code
expect(result).toMatch(/export default {[\s\S]*};/);
});
});