我在API文档中有一个非常简单的AsyncTypeahead示例:
import {AsyncTypeahead} from "react-bootstrap-typeahead";
import React, {Component} from "react";
class AsyncTest extends Component<Props, State> {
constructor() {
super()
this.state = {
isLoading:false,
options:{}
}
}
render() {
return <AsyncTypeahead
disabled={true}
isLoading={this.state.isLoading}
onSearch={query => {
this.setState({isLoading: true});
fetch(`https://api.github.com/search/users?q=123`)
.then(resp => resp.json())
.then(json => this.setState({
isLoading: false,
options: json.items,
}));
}}
options={this.state.options}
/>
}
}
export default AsyncTest;现在,如果我想创建这个组件的Jest快照测试,那么我将编写如下所示的内容:
import React from 'react';
import renderer from "react-test-renderer";
import AsyncTest from "./AsyncTest";
describe('Async Test', () => {
test('test', () => {
const test= <AsyncTest/>
expect(renderer.create(test).toJSON()).toMatchSnapshot();
});
});这不管用。我知道这个错误:
TypeError:无法读取属性‘样式’的null
(A:\frontend\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:524:20) at copyStyles (A:\frontend\node_modules\react-bootstrap-typeahead\lib\containers\hintContainer.js:61:27) at HintedInput.componentDidMount (A:\frontend\node_modules\react-bootstrap-typeahead\lib\containers\hintContainer.js:113:9) at commitLifeCycles (A:\frontend\node_modules\react-test-renderer\cjs\react-test-renderer.development.js:10930:22)
这是一个已知的问题引导打字机吗?
发布于 2019-10-09 14:58:09
同样的问题,这就是我的解决方案。罪魁祸首是预先输入的this容器,特别是这个函数:
function copyStyles(inputNode, hintNode) {
var inputStyle = window.getComputedStyle(inputNode);
/* eslint-disable no-param-reassign */
hintNode.style.borderStyle = interpolateStyle(inputStyle, 'border', 'style');
hintNode.style.borderWidth = interpolateStyle(inputStyle, 'border', 'width');
hintNode.style.fontSize = inputStyle.fontSize;
hintNode.style.lineHeight = inputStyle.lineHeight;
hintNode.style.margin = interpolateStyle(inputStyle, 'margin');
hintNode.style.padding = interpolateStyle(inputStyle, 'padding');
/* eslint-enable no-param-reassign */
}createMockNode的问题:来自inputNode的样式不是一个常见的对象,而是一个CSSStyleDeclaration,我不想完全模仿它。
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration
因此,当使用公共对象交换时,使用window.getComputedStyle不起作用。对我来说,最简单的解决方案也是模仿window.getComputedStyle。因此,第一部分是模拟触发错误的getComputedStyle函数。
global.window.getComputedStyle = jest.fn(x=>({}));但是仍然需要createNodeMock为输入节点提供一个空样式对象。
TLDR;快照与此片段一起工作
global.window.getComputedStyle = jest.fn(x=>({}));
const createNodeMock = (element) => ({
style: {},
});
const options={createNodeMock};
const tree = renderer
.create(form,options)
.toJSON();https://stackoverflow.com/questions/58199979
复制相似问题