2
votes

I'm having trouble mocking/testing this load-script package with jest: https://www.npmjs.com/package/load-script

import Footer from './Footer'
import { shallowMount } from '@vue/test-utils'
import { mocks } from '@test/components.spec-helper'
import load from 'load-script'

describe('Footer Component', () => {
  const wrapper = shallowMount(PageFooter, { mocks })
  jest.spyOn('load-script', 'load')
  it('should render the component correctly', () => {
    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should call load function', () => {
    expect(load).toHaveBeenCalledWith('mockUrl')
  })
Footer.vue

import load from 'load-script'

export default {
  name: 'Footer',
  mounted () {
    load('mockUrl')
  },

Error: Cannot spyOn on a primitive value; string given

The main problem seems to be jest won't let me spy on the load method from the 'load-script' package... Not sure what this line should be for it to work:

jest.spyOn('load-script', 'load')

the first argument shouldn't be a string it should be the module as an object, but i'm not sure what it should be when the package is called 'load-script'

1
jest.mock("load-script")? - jonrsharpe
what would assertion be? - yxu296
jest.spyOn('load-script', 'load') doesn't make sense. You're trying to spy on a string, not an object. Try to spy on * import. Also, there's no load method. It's default. - Estus Flask

1 Answers

0
votes

To spy on the load method you need to change a couple of things on your test.

  1. Use the * import like: import * as loadScript from 'load-script'

  2. Make sure you import the library first and the component after so that the spy can be injected before the component loads it. So move the ./Footer import below the 'load-script' import

  3. You need to spy before rendering the component, because if you spy after the component has been mounted it will be too late.

const loadSpy = jest.spyOn(loadScript, 'load')
const wrapper = shallowMount(PageFooter, { mocks })
  1. You check if the method you are spying on was called
expect(loadSpy).toHaveBeenCalledWith('mockUrl')

So the complete code should look like

import * as loadScript from 'load-script'
import { shallowMount } from '@vue/test-utils'
import { mocks } from '@test/components.spec-helper'
import Footer from './Footer'

describe('Footer Component', () => {
  const loadSpy = jest.spyOn(loadScript, 'load')
  const wrapper = shallowMount(PageFooter, { mocks })

  it('should render the component correctly', () => {
    expect(wrapper.html()).toMatchSnapshot()
  })

  it('should call load function', () => {
    expect(loadSpy).toHaveBeenCalledWith('mockUrl')
  })
})