Skip to content
This repository has been archived by the owner on May 6, 2024. It is now read-only.

Commit

Permalink
feat(babel): warn user if mock is used in closures
Browse files Browse the repository at this point in the history
  • Loading branch information
anilanar committed Feb 7, 2020
1 parent 7e74514 commit e24fe4c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
13 changes: 5 additions & 8 deletions babel-plugin-joke/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,19 +79,16 @@ bar.mockReturnValue(5);"
`);
});

it("ignores mock calls inside closures", async () => {
const result = await assert(`
it("throws error if mock is called inside closures", async () => {
const result = assert(`
import { mock } from '@userlike/joke';
beforeEach(() => {
const { foo } = mock(import('foo'));
});
`);
expect(result).toMatchInlineSnapshot(`
"import { foo as _foo } from \\"foo\\";
import { mock } from '@userlike/joke';
jest.mock(\\"foo\\");
beforeEach(() => {});"
`);
expect(result).rejects.toMatchInlineSnapshot(
`[Error: /example.ts: Can only use \`mock\` at the top-level scope.]`
);
});

it("throws a sensible error", async () => {
Expand Down
9 changes: 8 additions & 1 deletion babel-plugin-joke/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,14 @@ export default function UserlikeJoke({
})
.map(path => path.parentPath);

const mockRefPaths = namedMockRefs.concat(namespaceMockRefs);
const mockRefPaths = namedMockRefs
.concat(namespaceMockRefs)
.filter(path => {
if (path.scope.getProgramParent() !== path.scope) {
throw new Error("Can only use `mock` at the top-level scope.");
}
return true;
});

mockRefPaths.forEach(process(t, path));
}
Expand Down

0 comments on commit e24fe4c

Please sign in to comment.