manou
manou

Reputation: 133

How can I test a react component depending on an external legacy JS library

I have in a component this piece of code

enter image description here

TagCanvas is defined in the _app.tsx file within a legacy JS script. I need to do like that because if I include it in the component using it doesn't work when the component is rendered again.

enter image description here

I want to test this component, so I have started rendering the component like this:

import {render, screen} from '@testing-library/react';
import {MusasCloud} from '../../../components/MusasCloud.tsx';

const TagCanvas = jest.fn();
describe('MusasCloud component', () => {
    test('Should render the MusasCloud component', () => {
        render(<MusasCloud musas={[]} />);
        screen.debug();
    });
});

I get the html rendered as I expect but I am getting the Canvas error which I would like to avoid.

enter image description here

As you can see I have tried to mock the TagCanvas function using jest.fn() but this is not ding the job I'd expect.

Question: How can I avoid this exception when running the test?

Upvotes: 0

Views: 548

Answers (2)

manou
manou

Reputation: 133

Thanks to Marek response I have it now working.

It also worked if I do this global definition inside the beforeAll process.

enter image description here

I haven't jest configured to read the setupTest.js file. Since I am working in next in this project here is how I added it:

//jest.config.js
const nextJest = require('next/jest');

const createJestConfig = nextJest({
    dir: './',
});

// Add any custom config to be passed to Jest
const customJestConfig = {
    moduleDirectories: ['node_modules', '<rootDir>/'],
    testEnvironment: 'jest-environment-jsdom',
    // Define setupTest file here
    setupFiles: ['<rootDir>/setupTest.js'],
};

module.exports = createJestConfig(customJestConfig);

Upvotes: 0

Marek Rozmus
Marek Rozmus

Reputation: 968

Try to add the mock to your global in your setupTest.js file:

global.TagCanvas = {
  Start: () => "this is the mocked implementation"
}

Upvotes: 1

Related Questions