For my project, I developed a component intended to function as a module. The implementation involves the utilization of third-party code provided in the form of a config file (initOpinionLab.js
) and a .min.js file (opinionlab.min.js
). As part of the development process, I am actively working on writing unit tests for this component. One of the challenges I encountered was dealing with a minified module that the index.js file relies on, located at ../vendor/opinionlab.min.js
.
Given that this component is utilized as a node module, I decided to create a __mocks__
file next to the node_modules
directory, following the guidelines outlined in https://jestjs.io/docs/en/manual-mocks.html. This ensures that when the index.spec.js file attempts to locate the module, it will refer to the mock file. However, the question arises - How do I effectively mock a minified module if its functionality and return values are unknown? To address this, I created a placeholder export function as shown below:
In the 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()
})
})