News Articles jestjs

How to write test for RepositoryFactory in Vue.js/Nuxt.js

Summery I’ve implemented RepositoryFactory pattern for API connection in Vue.js/Nuxt.js application. hogeRepository.ts import { NuxtAxiosInstance } from ‘@nuxtjs/axios’ type queryData = { q: string | null } export const HogeRepository = ($axios: NuxtAxiosInstance) => ({ createResource (apiVersion: Number) { return `v${apiVersion}/meetings` }, get (data: queryData, version = 1) { const url = `${this.createResource(version)}` return […]

Not able to use exported HOC wrapped component in enzyme

This is a storybook component, and I’m unable to use the exported components either AssignmentWizardContent nor TestComponent to be used inside of shallow(). It give a prop mismatch error. If someone could explain this issue, that’d be very helpful. Thanks in advance. here Form.create() is from antd v3 Library Component.js export interface IAssignmentWizardContentProps { wizardprops:{ […]

getWrappingComponent in Jest/Enzyme tests

I am running into issues testing my application after implementing an analytics component to track usage. I kept getting an error saying the <Analytics Provider> must be called or related configuration provided as an argument so I tried passing a wrapper component when I render using shallow: describe(‘is loading’, () => { const component = […]

Mocked or skipping beforeEnter route guards during testing Vue Jest

I want to testing routes using Vue Test Utils and Jest but need mocked authentication or skipping beforeEnter, how to do this? myRoute.router.js: import {requireAuth} from ‘…/src/router-middleware’ ….. export default [ {path: ‘/dashboard’, component: Dashboard, beforeEnter: requireAuth, name: ‘overview’}, …..] myRoute.router.spec.js: import { shallowMount, createLocalVue } from ‘@vue/test-utils’ import VueRouter from ‘vue-router’ import routes from […]

Buefy error when testing with jest – vuejs

Im geting this error: [Vue warn]: Unknown custom element: <b-taginput> – did you register the component correctly? For recursive components, make sure to provide the "name" option. on this test: import MultipleChoice from ‘@/components/MultipleChoice’; import Buefy from ‘buefy’; const localVue = createLocalVue(); localVue.use(Buefy); describe(‘MultipleChoice.vue’, () => { let wrapper; beforeEach(() => { wrapper = shallowMount(MultipleChoice, […]

Jest – How to mock the implementation of a library that is called with a constructor?

I’m trying to mock a library called postmark, here’s my code: const postmark = require(‘postmark’); const postmarkClient = new postmark.ServerClient(process.env.POSTMARK_API); await postmarkClient.sendEmailWithTemplate({ From: ``, To: ’’, TemplateAlias: ‘template-example’, Tag: ‘any_tag’, TemplateModel: ‘any_template’ }); I’ve been mocking the implementation of a lot of different libraries in this project, so I think that the problem with postmark […]

How to unit test a function inside a Higher Order Function in JavaScript?

How to adapt unit tests for an existing function that needs to be wrapped in a Higher Order Function? I have two functions. getServerProps() fetching data and isAuthenticated() checking user authentication. Both in separate modules with their own unit tests. export function isAuthenticated(getServerProps) { return async function (param1, param2, param3) { const isLoggedIn = await […]

jest-util breaks when running a test

I have no idea what’s going on, when running npm run test Jest will break when processing the file from below. I have no context of what it’s causing it aside from jest-util breaking. Is this a known bug? I cannot properly upgrade this application at the moment. Version 20.0.4 Steps to reproduce I have […]

How to test useEffect with Auth api and state inside

useEffect(()=>{ Auth.currentAuthenticatedUser().then((user) => { setUser(user) setIsLoading(false) if (user.challengeName === ‘NEW_PASSWORD_REQUIRED’) { navigate(‘/ForceChangePassword’) } else{ navigate(‘/App’) } }).catch(error => { console.log(‘isCurrentAuthenticatedUser- ‘,error) setUser(null) setIsLoading(false) }) }); Source: React – Stack Overflow

ReactJs unit testing with jest and enzyme

I have the following return method in one of my components (AreaCodesTable): <> <Button id="create-email-template" className="p-button-rounded p-button-text p-button-icon-only blubicon-plus" onClick={() => this.toggleCreateAreaCodeModal()} ></Button> <Tooltip target={"#create-email-template"} content={this.props.t("common.areaCode")} position={"left"} /> <DataTable dataKey="id" id="area-codes-table" value={this.props.rootStore.areaCodeStore.areaCodes} > <Column key="title" field="title" header={this.props.t("areaCodes.shared.title")} style={{ width: "11rem" }} /> <Column key="description" field="description" header={this.props.t("areaCodes.shared.description")} style={{ width: "11rem" }} /> <Column body={this.showButtons} headerStyle={{ width: […]

testing-library cause change event to fire when testing vue v-text-field

I have a vue v-text-field: <v-text-field label="x" data-testid="value2x" v-model="displacement.value2[0]" @change="onUpdate()" > And a function that onUpdate that calls saveChanges when the change event is fired (on lost focus or enter pressed): @Inject() modelViewPortSync: ModelViewPortSync<ModelData> | undefined onUpdate () { if (this.modelViewPortSync) { this.modelViewPortSync.saveChanges() } } I’m attempting to test this using the testing-library and jest […]

Test suite failed to run: ReferenceError: window is not defined

I am failing a test suite after importing the component mentioned in the screenshot. How do I update the following test suite error? Source: React – Stack Overflow

React mocked a custom hook method, but it has not been called

In the component, a button will call a method from a custom hook import { useXxxApis } from "../xxx"; const xxxApis = useXxxApis(); <Button onClick={ () => { xxxApis.sendToXX(); } } /> When I write the test cases, one of the test is to make sure this sendToXX is called. const mockSendToXX = jest.fn(); jest.mock("../xxx", […]

Why does shallow rendering work and testing library render does not with final form component

Currently I have a react component that returns a Form from react-final-form. I am trying to write a test suite for the component using testing-library instead of enzyme. When I shallow render the component with enzyme it works fine but I really want to be using testing-library and when I utilize render I get the […]

Jest React – Test suite failed to run, Cannot find module ‘react-dotenv’

I used Create React App to make a new project, and now i try to implement each feature i will need. I am facing an issue i dont understand while trying to configure jest with reactjs. One my node_modules, react-dotenv break jest test. If i try to copy/past the issue line import env from ‘react-dotenv’; […]

testing Modals using Jest and Enzyme

I have a component below containing two modals ,and i need to cover this code with test const [showEditBusinessPhone, setShowEditBusinessPhone] = useState(false); return ( <> <EditHomePhone show={showEditHomeModal} handleCancel={() => setShowEditHomeModal(false)} handleSave={() => {}} /> <EditBusinessPhone show={showEditBusinessPhone} handleCancel={() => setShowEditBusinessPhone(false)} handleSave={() => {}} /> </> so there are the two models and I show each one […]

How to mock the post method in jest

This is Login Page, the post method should be mocked using the jest framework how it should be done using jest framework using mock please suggest me. import React, { useState } from "react"; import ‘bootstrap/dist/css/bootstrap.min.css’; import ‘./Login.css’; import SuccesAlert from "./SuccesAlert"; import ErrorAlert from "./ErrorAlert"; import {Button,Form} from ‘react-bootstrap’; export default function Login() { […]

Testing for SVG element in Jest (React-Redux)

I have a User component defined for a Reddit app like so: // User.js import React from "react"; import { useSelector } from "react-redux"; import { selectUsername, selectAuthState } from "./userSlice"; import Reddit from "../../api/Reddit"; const User = () => { const userID = useSelector(selectUsername); const authState = useSelector(selectAuthState); const { isLoading } = useSelector(state […]

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.