如何使用样式组件 createGlobalStyle 进行快照测试?
测试使用 jest v22.4.4、styled-components v4.1.2、react v16.7、jest-styled-components v5.0.1 和react-test-renderer v16.6.3 运行
快照的输出没有CSS。但我需要一种方法来测试 css 是否发生了变化...
例如
const BaseCSS = createGlobalStyle`
a { color: red };
`;
还有测试
import React from 'react';
import renderer from 'react-test-renderer';
import 'jest-styled-components';
import { BaseCSS } from '../src';
test('test if e', () => {
const tree = renderer.create(<div><BaseCSS /> Test</div>).toJSON();
expect(tree).toMatchSnapshot();
});
编辑:
快照的输出如下所示:(快照中没有CSS)
exports[`test if e 1`] = `
<div>
Test
</div>
`;
我在这里找到了答案,它有效! 全局样式组件将“存在”在 标签中,而不是在 内部,因此“您应该瞄准头部”。
这是我的工作示例:
import "jest-styled-components";
import React from "react";
import renderer from "react-test-renderer";
import GlobalStyle from "../../src/styles/GlobalStyle.js";
it("should have global style", () => {
renderer.create(<GlobalStyle />);
expect(document.head).toMatchSnapshot();
});
必须结合一些现有的解决方法才能到达这里,该代码是不言自明的
全局样式.tsx
export const GlobalStyles = createGlobalStyle`
button,
fieldset,
input {
all: unset;
}
}
setupTests.ts
export const globalStyleInjector = new GlobalStyleInjector();
globalStyleInjector.init();
GlobalStyles.test.tsx
import renderer from "react-test-renderer";
import { GlobalStyles } from "./GlobalStyles";
import { globalStyleInjector } from "../setupTests";
function formElement(styleTags: string) {
const template = document.createElement("template");
template.innerHTML = styleTags;
const styledComponentsElement = template.content.firstChild;
return styledComponentsElement;
}
class GlobalStyleInjector {
private styleTag: string = "";
public setStyle(style: string[] = []) {
this.styleTag = `<style>${style.join(" ")}</style>`;
}
public getStyleTag() {
return this.styleTag;
}
init() {
jest.mock("styled-components", () => {
const originalModule = jest.requireActual("styled-components");
const createGlobalStyle = (css: any[], ...rest: any[]) => {
this.setStyle(css);
return originalModule.createGlobalStyle(css, ...rest);
};
return {
__esModule: true,
...originalModule,
createGlobalStyle: jest.fn(createGlobalStyle)
};
});
}
}
describe("GlobalStyle", () => {
it("renders properly", () => {
renderer.create(<GlobalStyles />);
document.head.appendChild(
formElement(globalStyleInjector.getStyleTag()) as ChildNode
);
expect(document.head).toMatchSnapshot();
});
});
GlobalStyles.test.tsx.snap
// Jest Snapshot v1
exports[`GlobalStyle renders properly 1`] = `
<head>
<style>
button,
fieldset,
input {
all: unset;
}
</style>
</head>
`;