import { render } from '@testing-library/react';
import React from 'react';
import type { ComponentType } from 'react';
jest.mock('../is-server-environment', () => ({
isServerEnvironment: () => false,
}));
describe('', () => {
let consoleErrorSpy: jest.SpyInstance;
beforeEach(() => {
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
consoleErrorSpy.mockRestore();
document.head.innerHTML = '';
});
// We want to isolate the test to correctly mimic the environment being loaded in once
const createIsolatedTest = (callback: (Style: ComponentType) => void) => {
jest.isolateModules(() => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Style = require('../style');
callback(Style.default);
});
};
it('should render nothing on the client', () => {
createIsolatedTest((Style) => {
const { baseElement } = render();
expect(baseElement.getElementsByTagName('style')).toHaveLength(0);
expect(console.error).not.toHaveBeenCalled();
});
});
it('should add style to the head on the client', () => {
createIsolatedTest((Style) => {
render();
expect(document.head.innerHTML).toInclude('');
expect(console.error).not.toHaveBeenCalled();
});
});
it('should only add one style if it was already added', () => {
createIsolatedTest((Style) => {
render();
render();
expect(document.head.innerHTML).toIncludeRepeated('', 1);
expect(console.error).not.toHaveBeenCalled();
});
});
it('should noop in prod', () => {
createIsolatedTest((Style) => {
process.env.NODE_ENV = 'production';
render();
expect(console.error).not.toHaveBeenCalled();
});
});
it('should warn in dev when using a dangerous pseduo selector', () => {
createIsolatedTest((Style) => {
process.env.NODE_ENV = 'development';
render();
expect(console.error).toHaveBeenCalledTimes(1);
});
});
it('should warn in dev only once', () => {
createIsolatedTest((Style) => {
process.env.NODE_ENV = 'development';
render();
render();
expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledWith(
expect.stringMatching('Selectors ":first-child, :nth-child" are dangerous to use')
);
});
});
it('should render style tags in buckets', () => {
createIsolatedTest((Style) => {
render(
);
expect(document.head.innerHTML.split('').join('\n')).toMatchInlineSnapshot(`
"
"
`);
expect(console.error).not.toHaveBeenCalled();
});
});
it('should update styles', () => {
createIsolatedTest((Style) => {
const { rerender } = render();
rerender();
expect(document.head.innerHTML).toInclude('.second-render { display: block; }');
expect(console.error).not.toHaveBeenCalled();
});
});
});