Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add error message when mock is missing export #1819

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/mocks/src/default.ts
@@ -0,0 +1 @@
export default 'a default'
1 change: 1 addition & 0 deletions examples/mocks/src/example.ts
Expand Up @@ -25,3 +25,4 @@ export const number = 123
export const string = 'baz'
export const boolean = true
export const symbol = Symbol.for('a.b.c')
export default 'a default'
24 changes: 22 additions & 2 deletions examples/mocks/test/factory.test.ts
Expand Up @@ -6,6 +6,9 @@ import logger from '../src/log'
vi
.mock('../src/example', () => ({
mocked: true,
then: 'a then export',
square: (a: any, b: any) => a + b,
asyncSquare: async (a: any, b: any) => Promise.resolve(a + b),
}))

// doesn't think comments are mocks
Expand Down Expand Up @@ -40,10 +43,27 @@ vi.mock('../src/log.ts', async () => {
}
})

vi.mock('../src/default', () => 'a new default')

describe('mocking with factory', () => {
test('successfuly mocked', () => {
test('missing exports on mock', () => {
expect(() => example.default).toThrowError('[vitest] No "default" export is defined on the "mock:/src/example.ts"')
expect(() => example.boolean).toThrowError('[vitest] No "boolean" export is defined on the "mock:/src/example.ts"')
expect(() => example.object).toThrowError('[vitest] No "object" export is defined on the "mock:/src/example.ts"')
expect(() => example.array).toThrowError('[vitest] No "array" export is defined on the "mock:/src/example.ts"')
expect(() => example.someClasses).toThrowError('[vitest] No "someClasses" export is defined on the "mock:/src/example.ts"')
})

test('missing object return on factory gives error', async () => {
await expect(() => import('../src/default').then(m => m.default)).rejects
.toThrowError('[vitest] vi.mock("../src/default", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?')
})

test('defined exports on mock', async () => {
expect((example as any).then).toBe('a then export')
expect((example as any).mocked).toBe(true)
expect(example.boolean).toBeUndefined()
expect(example.square(2, 3)).toBe(5)
expect(example.asyncSquare(2, 3)).resolves.toBe(5)
})

test('successfuly with actual', () => {
Expand Down
30 changes: 29 additions & 1 deletion packages/vitest/src/runtime/mocker.ts
Expand Up @@ -108,7 +108,25 @@ export class VitestMocker {
return cached
const exports = await mock()
this.moduleCache.set(dep, { exports })
return exports

const exportHandler = {
get(target: Record<string, any>, prop: any) {
const val = target[prop]

// 'then' can exist on non-Promise objects, need nested instanceof check for logic to work
if (prop === 'then') {
if (target instanceof Promise)
return target.then.bind(target)
}
else if (val === undefined) {
throw new Error(`[vitest] No "${prop}" export is defined on the "${dep}"`)
}

return val
},
}

return new Proxy(exports, exportHandler)
}

private getMockPath(dep: string) {
Expand Down Expand Up @@ -336,6 +354,16 @@ export class VitestMocker {
}

public queueMock(id: string, importer: string, factory?: () => unknown) {
const factoryHandler = {
apply(target: () => unknown) {
const value = target()
if (typeof value !== 'object')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should also check null, i think?

throw new Error(`[vitest] vi.mock("${id}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`)
return value
},
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need a proxy, if we can just check it here:
https://github.com/jereklas/vitest/blob/bdd74e50836a70d9aae410781f5c6fdbe5093f3a/packages/vitest/src/runtime/mocker.ts#L109
?

Factory can also return a promise that resolves to primitive

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need the proxy on the exports object because you don't know which export is being accessed until the calling code imports something?

I need to head to bed, but will try taking a look at your factory related concern tomorrow.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do need a roxy for exports object, but I don't see why we need proxy for calling a factory - we are calling it ourselves on https://github.com/jereklas/vitest/blob/bdd74e50836a70d9aae410781f5c6fdbe5093f3a/packages/vitest/src/runtime/mocker.ts#L109

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah gotcha. I misunderstood your statement.


factory = factory === undefined ? factory : new Proxy(factory, factoryHandler)
VitestMocker.pendingIds.push({ type: 'mock', id, importer, factory })
}

Expand Down