nuxt-community / dayjs-module

Day.js module for your Nuxt 2 project.
https://www.npmjs.com/package/@nuxtjs/dayjs
MIT License
261 stars 16 forks source link

Jest testing: TypeError: $dayjs is not a function #296

Open mmeester opened 3 years ago

mmeester commented 3 years ago

I'm trying to use dayjs in one of our tests but keep running into the following TypeError:

TypeError: $dayjs is not a function

It seems like dayjs isn't part of the context:

PublishDate.vue

setup(props) {
  const { $dayjs } = useContext()

  const formattedDate = ref(false)

  if (props.date && dateRegex.test(props.date)) {
    formattedDate.value = $dayjs(props.date).format(props.format)
  }

  return {
    formattedDate,
  }
}

PublisDate.spec.js

import { mount } from '@vue/test-utils'
import PublishDate from '@/components/Atom/PublishDate.vue'

describe('Badge', () => {
  test('Expect date to show "February 2021"', () => {
    const wrapper = mount(PublishDate, {
      propsData: {
        date: '2021-02-06T17:22+02:00',
      },
    })

    const PublishDateEl = wrapper.find('time')
    expect(PublishDateEl.element.textContent).toBe('February 2021')
  })
})
potato4d commented 3 years ago

@mmeester Cloud you build a minimal Codesandbox that can reproduce the phenomenon and provide the URL?

mmeester commented 3 years ago

@potato4d https://codesandbox.io/s/competent-gauss-ymdjm

mmeester commented 3 years ago

any ideas about this?

christian-bravo7 commented 3 years ago

Hi @mmeester, meanwhile you can create a mock of $dayjs into $nuxt.context for your test, like this:

import dayjs from 'dayjs';
import { mount } from "@vue/test-utils";

import PublishDate from "@/components/PublishDate.vue";

// Waiting on response for this ticket to see how we can solve this (https://github.com/nuxt-community/dayjs-module/issues/296)
describe("Badge", () => {
  test('Expect date to show "February 2021"', () => {
    const wrapper = mount(PublishDate, {
      propsData: {
        date: "2021-02-06T17:22+02:00"
      },
      mocks: {
        $nuxt: {
          context: {
            $dayjs: dayjs
          },
        },
      },
    });

    const PublishDateEl = wrapper.find("time");
    expect(PublishDateEl.element.textContent).toBe("February 2021");
  });
});

I think you can add a global mock for $dayjs in your jest.config.js#setupFiles


// jest-setup-file.js
import dayjs from 'dayjs';
import { config } from '@vue/test-utils';

config.mocks = {
  $nuxt: {
    $context: {
      $dayjs: dayjs
    }
  }
}```
rstainsby commented 4 months ago

Any progress on this? We are still encountering this issue, @christian-bravo7's solution no longer works with Nuxt's recommended approach for unit testing components