Having trouble with Jest tests after transitioning to TypeScript

After transitioning my project from vanilla JavaScript to TypeScript, I encountered a strange issue with some test cases breaking. Despite everything running smoothly before the switch, certain tests using Vue.js, vue-test-utils, and jest are now failing.

jest.config.js

module.exports = {
    collectCoverageFrom: [
        '/src/**/*.{js,jsx,vue}',
        '!**/node_modules/**',
        '!**/vendor/**',
    ],
    moduleFileExtensions: [
        'ts',
        'js',
        'json',
        'vue',
    ],
    transform: {
        '.*\\.(vue)$': 'vue-jest',
        '^.+\\.js$': 'babel-jest',
        '^.+\\.ts$': 'ts-jest',
    },
    transformIgnorePatterns: [
        '<rootDir>/node_modules/(?!vuex-class-modules).+\\.js$',
    ],
    moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
    },
    setupFilesAfterEnv: [
        '@testing-library/jest-dom/extend-expect',
    ],
};

One specific example of a failing test that previously worked perfectly fine is as follows:

some.test.js

function mountStore(loggedInState) {
    const store = new Vuex.Store({
        modules: {
            customer: {
                namespaced: true,
                state: {
                    isLoggedIn: loggedInState,
                },
                actions,
            },
        },
    });

    return shallowMount(Component, {
        localVue,
        store,
        router,
        stubs: { 'router-link': RouterLinkStub },
    });
}

describe('Test with customer logged in at beginning', () => {
    let wrapper;

    beforeEach(() => {
        wrapper = mountStore(true);
    });

    it('should redirect to home if user is logged in on init', () => {
        expect(wrapper.vm.$route.name).toBe('Home');
    });
});

However, when running this particular test case, the outcome is unexpected:

expect(received).toBe(expected) // Object.is equality

Expected: "Home"
Received: null

Moreover, updating dependencies (including Jest dependencies) resulted in even more test failures. This leads me to believe that the introduction of TypeScript may have caused compatibility issues with certain dependencies, but pinpointing the exact combination causing problems remains elusive.

Some of the key dependencies that were updated and subsequently caused additional test failures include:

  • jest
  • ts-jest
  • babel-jest

Answer №1

Include

configuration: 'ts-jest/presets/js-with-babel',

in your jest.config.js file if you are using ts-jest along with babel-jest. Check the source for more information.

Answer №2

Dealing with a similar problem, I found the solution provided by @winwiz1 to be effective. However, in my case, I had to ensure that it was placed within the project definition due to my use of the projects syntax. I would have preferred to leave this feedback as a comment on @winwiz1's response but unfortunately StackOverflow messes up the formatting.

projects: [
    {
      "displayName": "test-unit",
      "preset": "ts-jest",
      "testMatch": ["<rootDir>/test-unit/**/*\.tests\.[t|j]s"]
    }
  ],

Answer №3

Have you considered including @types/jest? Make sure to add it to your tsconfig.json:

"types": ["@types/node", "@nuxt/types", "@types/jest", "nuxt-i18n"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with React occurring when attempting to delete an input component

I seem to be facing a challenge that I can't quite figure out whether it's related to React or not. To help illustrate the issue, I've created a simple example outside of my project: https://codepen.io/as3script/pen/VMbNdz?editors=1111 Wit ...

Displaying data from nested arrays using Vue.js, Axios, and API calls in the

Extracting data from an API with the following structure - Array ( [lastUpdate] => 1571616000 [lanuage] => en [data] => Array ( [0] => Array ( [itemId] => 1e3ac1f-6f1ddb0-5 ...

JavaScript code does not seem to be functioning correctly when integrated with Vue.js

When using Vuejs/Laravel, I utilize this simple JavaScript code to generate a chart within the blade. <script> function getData(columnOrder, keyName) { var obj, table = $("#t4"), array = []; table.find('tbody tr').each(function() { ...

Can an L1 VPC (CfnVpc) be transformed into an L2 VPC (IVpc)?

Due to the significant limitations of the Vpc construct, our team had to make a switch in our code to utilize CfnVpc in order to avoid having to dismantle the VPC every time we add or remove subnets. This transition has brought about various challenges... ...

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...

Adding Javascript and CSS files to the document dynamically

I've created a custom jQuery plugin, but I need it to verify if jQuery is already loaded. If not, I want the plugin to load jQuery along with a few other necessary JavaScript files. Additionally, I want it to check if a specific CSS file has been load ...

Protractor and Jasmine fail to fulfill the promise of retrieving a webpage title

I am facing an issue with my protractor/jasmine test code where it only prints out 1 and 2, then hangs and times out. It seems like there might be a problem with the click() action on the button element or the promise on the getTitle method of the browser ...

Utilizing v-if and splice on users to select items from v-model

After following a tutorial, I have the code snippet below that I would like to enhance: <div style="margin-top: 10px;"> v-for="task in taskItems" :key="task.id" <q-icon :name="task.icon"/> <div ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Navigate to specific routes only when a user is signed in using the Route render feature in React Router

I'm having trouble figuring out how to display the signIn component when currentUser is not detected. There are no errors, but it's rendering an empty component because of the value "currentUser = null". <Routes> <Route exact path=&ap ...

If a user clicks on an element twice in a row, the div will be hidden. Otherwise, it will remain

My navigation bar consists of several items and a div located next to it, as shown below: <nav> <a id="a"></a> <a id="b"></a> <a id="c"></a> </nav> <div id="menu-col"></div> If the same li ...

Tips for reducing the size of Javascript code upon clicking a button while also implementing validations

I need help with a textEditor feature. I want users to be able to write Javascript functions, and when they click a button, the code should be validated for correct syntax and then minified. This functionality needs to be implemented using either Javascrip ...

In the XHTML mode, MathOverflow's invaluable mathematical expertise shines brightly

I am interested in incorporating the unique “piece of valuable flair™” from MathOverflow onto my website. The issue I am facing is that I want my webpage to comply with XHTML5 standards, meaning it should be served with the MIME type application/xht ...

Leveraging an external React library to utilize .ogg files for audio playback specifically in the Safari

Hey there! I'm currently working on incorporating ogg-opus audio playback in a react app on Safari (since it doesn't support .ogg format). My project was initialized using create-react-app. I came across the "ogv.js" library, which supposedly h ...

Can user authentication be done across various subdomains?

I am looking to develop a multi-tenant application using Laravel 8.0, incorporating the Laravel multi-tenancy package and Laravel Sanctum, with Vue Frontend for customers and a separate Vue Frontend for Admins. Vue2 Frontend for customers such as: example ...

What can be done to enhance this particular element?

I've created a Component that uses a 3rd party joke API to fetch jokes with a specific category upon page load. The component also includes a refresh button for fetching new jokes. export default function Jokes() { const { cat } = useParams(); const [ ...

Dreamweaver and jQuery collaboration for displaying PDFs in a container

I am currently utilizing the jQuery accordion functionality within the latest version of Dreamweaver. My goal is to link a specific PDF with each account so that when an account is selected, the corresponding PDF will open in the designated "content goes h ...

Does the sequence matter when studying JavaScript, Ajax, jQuery, and JSON?

Expanding my job opportunities is a top priority for me, which is why I am dedicated to learning JavaScript, AJAX, jQuery, and JSON. As I delve into these languages, I can see how they all have roots in JavaScript. My main inquiry is about the relationsh ...

Angular is not rendering styles correctly

Having two DOMs as depicted in the figures, I'm facing an issue where the circled <div class=panel-heading largeText"> in the first template receives a style of [_ngcontent-c1], while that same <div> gets the style of panel-primary > .p ...

Troubleshooting HTML drag and drop problems

My goal is to create an HTML form element that allows users to rank four items in their preferred order. For instance, I intend to prompt the user to select their favorite animal and arrange it accordingly. <!DOCTYPE html> <html lang="en"> < ...