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

Mocking native esm modules on fastify project fails #42

Open
anonrig opened this issue Mar 20, 2021 · 4 comments
Open

Mocking native esm modules on fastify project fails #42

anonrig opened this issue Mar 20, 2021 · 4 comments

Comments

@anonrig
Copy link

anonrig commented Mar 20, 2021

Hi everyone!

First of all thank you for everything related to testdouble. I'm having some trouble regarding a esm import in a fastify project I've been working on.

Here's the example code. getByAuthorization is a function called inside the prehandler middleware of a fastify endpoint. And the issue is, the function is not replaced, without giving any error or indication of the reason.

test('should throw forbidden on wrong x-key', async (t) => {
  await quibble.esm(
    path.join(path.resolve(''), '../src/models/application.js'),
    {
      getByAuthorization: async function () {
        return null
      },
    },
  )

  const { statusCode, body } = await server.inject({
    method: 'POST',
    url: '/v1/events',
    payload: [{ name: 'non-existent', timestamp: Date.now() }],
    headers: {
      'x-key': v4(),
      'x-client-id': v4(),
    },
  })
  const response = JSON.parse(body)

  t.is(statusCode, 403)
  t.is(response.error, 'Forbidden')
  t.truthy(response.message.includes('Invalid authorization key'))
})
@searls
Copy link
Member

searls commented Mar 20, 2021

whenever I hear ESM, I tag in @giltayar!

@giltayar
Copy link
Contributor

Will look into it tonight.

@giltayar
Copy link
Contributor

@anonrig you're import-ing the server before you're quibble.esm-ing, right? So that means that the server is importing application.js before you're quibble-ing, which means it gets the unimported version of the application. This would happen even if you use CJS.

To deal with that, await import the server after you quibble.esm. I may be misunderstanding, but I believe that's the problem.

BTW, td.replaceEsm is the same as quibble.esm. You don't really need to use quibble (although it's still fine).

@anonrig
Copy link
Author

anonrig commented Oct 27, 2021

Here I am, 6 months later, tackling with the same issue after solving it 6 months ago. 🗡️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants