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 1 commit
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/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'
17 changes: 15 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 @@ -41,9 +44,19 @@ vi.mock('../src/log.ts', async () => {
})

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

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
31 changes: 31 additions & 0 deletions packages/vitest/src/runtime/mocker.ts
Expand Up @@ -335,7 +335,38 @@ export class VitestMocker {
return this.request(dep)
}

private wrapFactoryInProxy(id: string, importer: string, factory?: () => unknown) {
if (!factory)
return factory

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 "${id}" mock defined here: ${importer}`)
}

return val
},
}

const factoryHandler = {
apply(target: () => Object) {
return new Proxy(target(), exportHandler)
},
}
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.


return new Proxy(factory, factoryHandler) as () => unknown
}

public queueMock(id: string, importer: string, factory?: () => unknown) {
factory = this.wrapFactoryInProxy(id, importer, factory)
Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Member

Choose a reason for hiding this comment

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

And while we are here, let's throw an error, if factory returns non-object. (With a help message that it should return { default }, if user wants to mock default export)

Copy link
Contributor Author

@jereklas jereklas Aug 8, 2022

Choose a reason for hiding this comment

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

I split the proxy objects. The export object proxy is now happening where you suggested, and the factory proxy object is now returning an error if the return value is not an object.

VitestMocker.pendingIds.push({ type: 'mock', id, importer, factory })
}

Expand Down