diff --git a/babel-plugin-joke/src/index.test.ts b/babel-plugin-joke/src/index.test.ts index 208043f..142ad51 100644 --- a/babel-plugin-joke/src/index.test.ts +++ b/babel-plugin-joke/src/index.test.ts @@ -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 () => { diff --git a/babel-plugin-joke/src/index.ts b/babel-plugin-joke/src/index.ts index 752e081..bf27722 100644 --- a/babel-plugin-joke/src/index.ts +++ b/babel-plugin-joke/src/index.ts @@ -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)); }