Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/schematics/angular/refactor/jasmine-vitest/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,34 @@ describe('Jasmine to Vitest Schematic', () => {
expect(newContent).toContain(`vi.spyOn(service, 'myMethod').mockReturnValue(undefined);`);
});

it('should report a nested done callback for manual migration', async () => {
const specFilePath = 'projects/bar/src/app/app.spec.ts';
appTree.overwrite(
specFilePath,
`
it('waits for a value', (done) => {
values.subscribe({ error: (error) => { done.fail(error); } });
ready.then(done);
});
`,
);

const logs: string[] = [];
schematicRunner.logger.subscribe((entry) => logs.push(entry.message));
const tree = await schematicRunner.runSchematic(
'refactor-jasmine-vitest',
{ project: 'bar', verbose: true },
appTree,
);

const content = tree.readContent(specFilePath);
expect(content).toContain('Please migrate manually.');
expect(content).toContain('done.fail(error)');
expect(content).toContain('ready.then(done)');
expect(logs).toContain(' - 1x unhandled-done-usage');
expect(logs.join('\n')).not.toContain('Transformed promise');
});

it('should only transform files matching the fileSuffix option', async () => {
const specFilePath = 'projects/bar/src/app/app.spec.ts';
const specFileContent = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,13 @@ describe('Jasmine to Vitest Transformer - Nested Transformations', () => {
});
`,
expected: `
it('should handle timers and async', async () => {
// TODO: vitest-migration: The 'done' callback was used in an unhandled way. Please migrate manually.
it('should handle timers and async', (done) => {
vi.useFakeTimers();
setTimeout(() => {
expect(true).toBe(true);
vi.useRealTimers();
done();
}, 100);
vi.advanceTimersByTime(100);
});
Expand Down Expand Up @@ -175,10 +177,12 @@ describe('Comment Preservation', () => {
});
`,
expected: `
it('should do something async', async () => {
// TODO: vitest-migration: The 'done' callback was used in an unhandled way. Please migrate manually.
it('should do something async', (done) => {
// Start the async operation
setTimeout(() => {
// It's done now
done();
}, 100);
});
`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,7 @@ export function transformPending(
function transformComplexDoneCallback(
node: ts.Node,
doneIdentifier: ts.Identifier,
refactorCtx: RefactorContext,
): ts.Node | ts.Node[] | undefined {
const { sourceFile, reporter } = refactorCtx;
if (
!ts.isExpressionStatement(node) ||
!ts.isCallExpression(node.expression) ||
Expand Down Expand Up @@ -193,12 +191,6 @@ function transformComplexDoneCallback(
return node;
}

reporter.reportTransformation(
sourceFile,
node,
'Transformed promise `.then()` with `done()` to `await`.',
);

const newThenCallback = ts.isArrowFunction(thenCallback)
? ts.factory.updateArrowFunction(
thenCallback,
Expand Down Expand Up @@ -230,9 +222,7 @@ function transformComplexDoneCallback(
function transformPromiseBasedDone(
callExpr: ts.CallExpression,
doneIdentifier: ts.Identifier,
refactorCtx: RefactorContext,
): ts.Node | undefined {
const { sourceFile, reporter } = refactorCtx;
if (
ts.isPropertyAccessExpression(callExpr.expression) &&
(callExpr.expression.name.text === 'then' || callExpr.expression.name.text === 'catch')
Expand Down Expand Up @@ -277,12 +267,6 @@ function transformPromiseBasedDone(
}

if (isDoneHandler) {
reporter.reportTransformation(
sourceFile,
callExpr,
'Transformed promise `.then(done)` to `await`.',
);

return ts.factory.createExpressionStatement(
ts.factory.createAwaitExpression(callExpr.expression.expression),
);
Expand Down Expand Up @@ -342,14 +326,20 @@ export function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContex

// Count total usages of 'done' in the body
const totalUsages = countDoneUsages(functionArg.body, doneIdentifier);
let handledUsages = 0;
let doneWasUsed = false;
const handledUsages: { node: ts.Node; message?: string }[] = [];

const bodyVisitor = (bodyNode: ts.Node): ts.Node | ts.Node[] | undefined => {
const complexTransformed = transformComplexDoneCallback(bodyNode, doneIdentifier, refactorCtx);
// Leave nested callbacks for manual migration unless their enclosing promise is awaited.
if (ts.isFunctionLike(bodyNode)) {
return bodyNode;
}

const complexTransformed = transformComplexDoneCallback(bodyNode, doneIdentifier);
if (complexTransformed !== bodyNode) {
doneWasUsed = true;
handledUsages++; // complex transform handles one usage
handledUsages.push({
node: bodyNode,
message: 'Transformed promise `.then()` with `done()` to `await`.',
});

return complexTransformed;
}
Expand All @@ -364,13 +354,10 @@ export function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContex
callExpr.expression.expression.text === doneIdentifier.text &&
callExpr.expression.name.text === 'fail'
) {
doneWasUsed = true;
handledUsages++;
reporter.reportTransformation(
sourceFile,
bodyNode,
'Transformed `done.fail()` to `throw new Error()`.',
);
handledUsages.push({
node: bodyNode,
message: 'Transformed `done.fail()` to `throw new Error()`.',
});
const errorArgs = callExpr.arguments.length > 0 ? [callExpr.arguments[0]] : [];

return ts.factory.createThrowStatement(
Expand All @@ -383,10 +370,12 @@ export function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContex
}

// Transform `promise.then(done)` or `promise.catch(done.fail)` to `await promise`
const promiseTransformed = transformPromiseBasedDone(callExpr, doneIdentifier, refactorCtx);
const promiseTransformed = transformPromiseBasedDone(callExpr, doneIdentifier);
if (promiseTransformed) {
doneWasUsed = true;
handledUsages++;
handledUsages.push({
node: callExpr,
message: 'Transformed promise `.then(done)` to `await`.',
});

return promiseTransformed;
}
Expand All @@ -396,8 +385,7 @@ export function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContex
ts.isIdentifier(callExpr.expression) &&
callExpr.expression.text === doneIdentifier.text
) {
doneWasUsed = true;
handledUsages++;
handledUsages.push({ node: callExpr });

return ts.setTextRange(ts.factory.createEmptyStatement(), callExpr.expression);
}
Expand All @@ -422,7 +410,7 @@ export function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContex
});

// Safety check: if we found usages but didn't handle all of them, abort.
if (handledUsages < totalUsages) {
if (handledUsages.length < totalUsages) {
reporter.reportTransformation(
sourceFile,
node,
Expand All @@ -435,10 +423,16 @@ export function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContex
return node;
}

if (!doneWasUsed) {
if (!handledUsages.length) {
return node;
}

for (const usage of handledUsages) {
if (usage.message) {
reporter.reportTransformation(sourceFile, usage.node, usage.message);
}
}

reporter.reportTransformation(
sourceFile,
node,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { expectTransformation } from '../test-helpers';
describe('Jasmine to Vitest Transformer - transformDoneCallback', () => {
const testCases = [
{
description: 'should transform an `it` block with a done callback to an async function',
description: 'should flag a done callback inside a timer for manual migration',
input: `
it('should do something async', (done) => {
setTimeout(() => {
Expand All @@ -21,9 +21,11 @@ describe('Jasmine to Vitest Transformer - transformDoneCallback', () => {
});
`,
expected: `
it('should do something async', async () => {
// TODO: vitest-migration: The 'done' callback was used in an unhandled way. Please migrate manually.
it('should do something async', (done) => {
setTimeout(() => {
expect(true).toBe(true);
done();
}, 100);
});
`,
Expand Down Expand Up @@ -89,7 +91,7 @@ describe('Jasmine to Vitest Transformer - transformDoneCallback', () => {
`,
},
{
description: 'should work with a custom done name',
description: 'should flag a nested callback with a custom done name',
input: `
it('should work with a custom done name', (finish) => {
setTimeout(() => {
Expand All @@ -98,12 +100,30 @@ describe('Jasmine to Vitest Transformer - transformDoneCallback', () => {
});
`,
expected: `
it('should work with a custom done name', async () => {
// TODO: vitest-migration: The 'done' callback was used in an unhandled way. Please migrate manually.
it('should work with a custom done name', (finish) => {
setTimeout(() => {
finish();
}, 100);
});
`,
},
{
description: 'should keep the done parameter when a nested done.fail cannot be migrated',
input: `
beforeEach((done) => {
service.onError(function (error) { done.fail(error); });
service.init().then(done);
});
`,
expected: `
// TODO: vitest-migration: The 'done' callback was used in an unhandled way. Please migrate manually.
beforeEach((done) => {
service.onError(function (error) { done.fail(error); });
service.init().then(done);
});
`,
},
{
description: 'should handle done in a finally block',
input: `
Expand Down