Skip to content

Commit

Permalink
fix(mock-api): provide an explainatory error message when the mocks A…
Browse files Browse the repository at this point in the history
…PI hoisting doesn't work (#1098)
  • Loading branch information
Guido D'Orsi committed Apr 6, 2022
1 parent 1696195 commit 0b6d980
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/vitest/src/node/plugins/mock.ts
Expand Up @@ -33,6 +33,13 @@ export function hoistMocks(code: string) {
return m
}

const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
You may encounter this issue when importing the mocks API from another module other than 'vitest'.
To fix this issue you can either:
- import the mocks API directly from 'vitest'
- enable the 'globals' options`

export const MocksPlugin = (): Plugin => {
return {
name: 'vitest:mock-plugin',
Expand All @@ -43,12 +50,22 @@ export const MocksPlugin = (): Plugin => {
if (m) {
// hoist vitest imports in case it was used inside vi.mock factory #425
const vitestImports = code.matchAll(vitestRegexp)
let found = false

for (const match of vitestImports) {
const indexStart = match.index!
const indexEnd = match[0].length + indexStart
m.remove(indexStart, indexEnd)
m.prepend(`${match[0]}\n`)
found = true
}

// if no vitest import found, check if the mock API is reachable after the hoisting
if (!found) {
m.prepend('try { vi } catch (_) { try { vitest } catch (__)'
+ `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) } }\n`)
}

return {
code: m.toString(),
map: m.generateMap({ hires: true }),
Expand Down
8 changes: 8 additions & 0 deletions test/fails/fixtures/mock-import-proxy-module.test.ts
@@ -0,0 +1,8 @@
import { expect, test, vi } from './proxy-module'

// This can be used only when imported directly from vitest
vi.mock('vite')

test('hi', () => {
expect(1 + 1).toEqual(2)
})
1 change: 1 addition & 0 deletions test/fails/fixtures/proxy-module.ts
@@ -0,0 +1 @@
export * from 'vitest'
2 changes: 2 additions & 0 deletions test/fails/test/__snapshots__/runner.test.ts.snap
Expand Up @@ -6,6 +6,8 @@ exports[`should fails > expect.test.ts > expect.test.ts 1`] = `"AssertionError:

exports[`should fails > hook-timeout.test.ts > hook-timeout.test.ts 1`] = `"Error: Hook timed out in 10ms."`;

exports[`should fails > mock-import-alias.test.ts > mock-import-alias.test.ts 1`] = `"Error: There are some problems in resolving the mocks API."`;

exports[`should fails > nested-suite.test.ts > nested-suite.test.ts 1`] = `"AssertionError: expected true to be false // Object.is equality"`;

exports[`should fails > stall.test.ts > stall.test.ts 1`] = `"TypeError: failure"`;
Expand Down

0 comments on commit 0b6d980

Please sign in to comment.