0

I created a component to be used as a package. We are using third party code supplied to us, a config file (initOpinionLab.js) and a .min.js file (opinionlab.min.js). I am trying to write unit tests for my component. A module that index.js is dependent upon is a minified file located here ../vendor/opinionlab.min.js.

Since this is a component that is used as a node module. I created a __mocks__ file adjacent to the node_modules directory (https://jestjs.io/docs/en/manual-mocks.html) so that when my index.spec.js file looks for this, it will look to the mocks file. How do I mock this minified module if I don't know what it does or returns? I just made this export function up.

root of app/__mocks__ /opinionlab.min.js

export const aFunctionFromOpinionLab = jest.fn(() => Promise.resolve({}))

src/index.js

import '../vendor/opinionlab.min'
import '../assets/style.css'
import initOpinionLab from './initOpinionLab'

export default {
  name: 'FeedbackLink',
  props: {
    linkText: {
      type: String,
      default: 'Feedback'
    },
    clientId: {
      type: String,
      default: null
    },
    flow: {
      type: String,
      default: null
    },
    srcCorrelationId: {
      type: String,
      default: null
    }
  },
  mounted () {
    console.log(this.clientId, this.flow, this.srcCorrelationId, 'this is from mounted line 26')
    initOpinionLab({
      clientId: this.clientId,
      flow: this.flow,
      srcCorrelationId: this.srcCorrelationId
    })
  },
  methods: {
    launchOpinionLab () {
      window.OOo.inlineFeedbackShow()
    }
  },
  template: '<a @click="launchOpinionLab" class="opinionlab-link">{{ linkText }}</a>'
}

src/index.spec.js

import FeedbackLink from '@src/index'
import { shallowMount } from '@vue/test-utils'

jest.mock('../vendor/opinionlab.min.js')

describe('FeedbackLink', () => {
  const wrapper = shallowMount(FeedbackLink, {
    propsData: {
      linkText: 'Feedback',
      clientId: 'abc12345',
      flow: 'NEW_USER',
      srcCorrelationId: 'xyz9876'
    }
  })
  it('[positive] should render correct contents', () => {
    expect(wrapper.html()).toMatchSnapshot()
  })
})
Kevin T.
  • 668
  • 3
  • 12
  • 29

1 Answers1

0

So you are trying to write unit test for a 3rd party library? This kind of goes against the idea of unit testing your code since you at some point have to assume the other code has its own unit test already. I understand you mocking the 3rd party code so you can get yours to run, but a mock should not care about how the code works, and instead just provides the needed output so your actual code can run.

I would suggest stubbing the code or just returning a known testable value so you can at minimum unit test your code, and not worry about the inner workings of the opinionlab.min.js , as the value gained from trying to parse through a minified fiel will not be worth the time.

Scornwell
  • 597
  • 4
  • 19