I've developed a chrome extension using React. I've started adding some tests, but I'm struggling with a few of them.
The issue lies in testing my <App/>
component, as I keep encountering errors no matter what approach I take.
Here's what I've tried:
import React from "react";
import { render, fireEvent } from "@testing-library/react";
import App from "../../App";
import { BMEUtils } from "../../app/helpers/utils/BMEUtils";
import { FormContainerID } from "../../app/dom-elements/_components/forms/AbsoluteContainer";
import renderer from 'react-test-renderer';
describe("tests ", () => {
it("test App", () => {
const component = renderer.create(
<App />,
);
const b = document.getElementById(FormContainerID)
const a = document.getElementById("login-btn");
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
expect(a).not.toBeNull();
expect(b).not.toBeNull();
});
});
However, I keep encountering an error during the test:
ReferenceError: chrome is not defined
This error occurs because one of the components references the chrome
namespace to add a listener (
chrome.runtime.onMessage.addListener
).
I've attempted the following solutions:
global.chrome = jest.fn() as any;
jest.mock('chrome');
import chrome from "sinon-chrome";
beforeAll(function () {
global.chrome = chrome as any;
});
const chrome = require('sinon-chrome/extensions');
beforeAll(function () {
global.chrome = chrome ;
});
var globalRef:any =global;
globalRef.chrome = jest.fn().mockImplementation();
const component = renderer.create(
<App />,
);
import { mount } from 'enzyme';
const wrapper = mount(
<App/>
);
const p = wrapper.find('#login-btn');
Unfortunately, none of these solutions have worked for me.
This remains my main issue.
Another problem I'm facing, which may be related to the previous one, is figuring out how to mock the implementation of certain functions that are executed internally and are not part of any modules.
For instance:
// Test as Base64 Image
// Utils is a namespace
test('base64Image', () => {
...
const file = ...;
let base64Image = Utils.asBase64Image(file);
expect(base64Image).not.toEqual("");
...
});
function asBase64Image(file:File) {
...
canvas.getContext("2d");
img.onload
...
}
To work around this, I've resorted to using Modules to replace these functions and mock them, such as replacing img.onload
with module.loadImage(img).then(...)
.
However, I'm eager to learn the correct way of doing this if possible.
Nevertheless, my current pressing issue is the inability to successfully test my <App/>
component.