Jest + Enzyme:如何测试图像 src?
Jest + Enzyme: How to test an image src?
我有一个 Logo 组件:
import React from "react";
import logo from "assets/images/logo.png";
const Logo = () => {
return <img style={{ width: 50 }} src={logo} alt="logo" />;
};
export default Logo;
测试文件:
import React from "react";
import Logo from "components/shared/Logo";
describe("<Logo />", () => {
it("renders an image", () => {
const logo = shallow(<Logo />);
expect(logo.find("img").prop("src")).toEqual("blahh");
});
});
但是当我运行测试的时候,出现了一些奇怪的错误:
$ NODE_PATH=src jest
FAIL src/tests/Logo.test.js
● <Logo /> › renders an image
TypeError: val.entries is not a function
at printImmutableEntries (node_modules/expect/node_modules/pretty-format/build/plugins/immutable.js:44:5)
at Object.<anonymous>.exports.serialize (node_modules/expect/node_modules/pretty-format/build/plugins/immutable.js:178:12)
我该如何测试图像 src === "assets/images/logo.png"?
像这样..
import React from "react";
import Logo from "components/shared/Logo";
describe("<Logo />", () => {
it("renders an image with src correctly", () => {
const wrapper= shallow(<Logo src="yourlogo.png" />);
expect(wrapper.html()).toEqual('<img src="yourlogo.png"/>'); // implement your ".toEqual(...)" to your Logo component result
});
});
或者,访问您的 src 道具:
const wrapper = mount(<Logo src="blah..."/>);
expect(wrapper.find({ prop: 'src' })).to.have.length(1); // or any other check you need
我假设您在 Logo 组件附近的 __test__
目录中编写测试。
无论如何,将您的“assets/images/logo.png”相对于您的测试文件导入。
如果你的项目结构是这样的
Project
├── assets
│ └── images
├ |
│ └── logo.png
├── src
│ └── components
├ |── Logo.js
│ └── __tests__
├ └── logo.test.js
└
首先,就像我说的那样,通过键入以下内容将图像导入您的 logo.test.js:
import React from 'react';
import {shallow} from 'enzyme';
import Logo from "./../Logo";
import logoImage from "./../../../assets/images/logo.png;
describe("<Logo />", () => {
it("renders an image", () => {
const logo = shallow(<Logo />);
expect(logo.find("img").prop("src")).toEqual(logoImage);
});
});
出于某种原因,此信息未明确突出显示。
在 'Integration with wepack' 部分显示了如何使用 transform
:
自动模拟静态资产
If moduleNameMapper cannot fulfill your requirements, you can use Jest's transform config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that require('logo.jpg'); returns 'logo') can be written as:
package.json
{
"jest": {
"transform": {
"\.(js|jsx)$": "babel-jest",
"\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
}
}
}
fileTransformer.js
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
所以这将使您的 wrapper.props().src
只是一个字符串(适用于任何类型的匹配器,例如 .toEqual
)。这也意味着 expect(wrapper).toMatchSnapshot()
也像尊重图像路径的魅力一样工作。
[upd] 不要错过在 config
中为 JS/JSX 文件指定 "babel-jest"
转换
/* **Image component** */
import React from "react";
import PropsTypes from "prop-types";
/** Image Component - This is shared component, You can use this component for rendering images
* @param (string) altName
* @param (string) fileName
* @Return element
*/
const Image = props => {
const { fileName, altName } = props;
return <img src={`/images/${fileName}`} alt={altName}></img>;
};
/* Apply validation on Text Component */
Image.propTypes = {
fileName: PropsTypes.string.isRequired,
altName: PropsTypes.string.isRequired
};
Image.defaultProps = {
fileName: "dummy.png",
altName: "dummy"
};
export default Image;
/* Image.test.js */
import React from "react";
import { shallow } from "enzyme";
import Image from "./Image";
describe("Testing of Image component", () => {
it("render image component with default value", () => {
const wrapper = shallow(<Image />);
expect(wrapper).toBeTruthy();
expect(wrapper.find("img").length).toEqual(1);
});
it("render image component with props ", () => {
const props = {
fileName: "facebook.png",
altName: "facebook"
};
const wrapper = shallow(<Image {...props} />);
expect(wrapper).toBeTruthy();
expect(wrapper.find("img").length).toEqual(1);
});
});
这对我有用...
组件:
function Header() {
return (
<div className="header">
<img src="images/logo.png" alt="no logo found"/>
</div>
)
}
测试:
it('should set logo image src correctly', () => {
const logoImg = mountedHeader.find('img')
expect(logoImg.getElement(0).props.src).toEqual("images/logo.png")
});
describe("CharacterInfo", () => {
const data={
image:"ricky.jpg",
}
it("should renders img src", () => {
const wrapper=shallow(<CharacterInfo image={data.image}/>);
});
const imgSrc= wrapper.find("img").prop('src');
expect(imgSrc).toBe("ricky.jpg");
})
我有一个 Logo 组件:
import React from "react";
import logo from "assets/images/logo.png";
const Logo = () => {
return <img style={{ width: 50 }} src={logo} alt="logo" />;
};
export default Logo;
测试文件:
import React from "react";
import Logo from "components/shared/Logo";
describe("<Logo />", () => {
it("renders an image", () => {
const logo = shallow(<Logo />);
expect(logo.find("img").prop("src")).toEqual("blahh");
});
});
但是当我运行测试的时候,出现了一些奇怪的错误:
$ NODE_PATH=src jest
FAIL src/tests/Logo.test.js
● <Logo /> › renders an image
TypeError: val.entries is not a function
at printImmutableEntries (node_modules/expect/node_modules/pretty-format/build/plugins/immutable.js:44:5)
at Object.<anonymous>.exports.serialize (node_modules/expect/node_modules/pretty-format/build/plugins/immutable.js:178:12)
我该如何测试图像 src === "assets/images/logo.png"?
像这样..
import React from "react";
import Logo from "components/shared/Logo";
describe("<Logo />", () => {
it("renders an image with src correctly", () => {
const wrapper= shallow(<Logo src="yourlogo.png" />);
expect(wrapper.html()).toEqual('<img src="yourlogo.png"/>'); // implement your ".toEqual(...)" to your Logo component result
});
});
或者,访问您的 src 道具:
const wrapper = mount(<Logo src="blah..."/>);
expect(wrapper.find({ prop: 'src' })).to.have.length(1); // or any other check you need
我假设您在 Logo 组件附近的 __test__
目录中编写测试。
无论如何,将您的“assets/images/logo.png”相对于您的测试文件导入。
如果你的项目结构是这样的
Project
├── assets
│ └── images
├ |
│ └── logo.png
├── src
│ └── components
├ |── Logo.js
│ └── __tests__
├ └── logo.test.js
└
首先,就像我说的那样,通过键入以下内容将图像导入您的 logo.test.js:
import React from 'react';
import {shallow} from 'enzyme';
import Logo from "./../Logo";
import logoImage from "./../../../assets/images/logo.png;
describe("<Logo />", () => {
it("renders an image", () => {
const logo = shallow(<Logo />);
expect(logo.find("img").prop("src")).toEqual(logoImage);
});
});
出于某种原因,此信息未明确突出显示。
在 'Integration with wepack' 部分显示了如何使用 transform
:
If moduleNameMapper cannot fulfill your requirements, you can use Jest's transform config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that require('logo.jpg'); returns 'logo') can be written as:
package.json
{
"jest": {
"transform": {
"\.(js|jsx)$": "babel-jest",
"\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
}
}
}
fileTransformer.js
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
所以这将使您的 wrapper.props().src
只是一个字符串(适用于任何类型的匹配器,例如 .toEqual
)。这也意味着 expect(wrapper).toMatchSnapshot()
也像尊重图像路径的魅力一样工作。
[upd] 不要错过在 config
中为 JS/JSX 文件指定"babel-jest"
转换
/* **Image component** */
import React from "react";
import PropsTypes from "prop-types";
/** Image Component - This is shared component, You can use this component for rendering images
* @param (string) altName
* @param (string) fileName
* @Return element
*/
const Image = props => {
const { fileName, altName } = props;
return <img src={`/images/${fileName}`} alt={altName}></img>;
};
/* Apply validation on Text Component */
Image.propTypes = {
fileName: PropsTypes.string.isRequired,
altName: PropsTypes.string.isRequired
};
Image.defaultProps = {
fileName: "dummy.png",
altName: "dummy"
};
export default Image;
/* Image.test.js */
import React from "react";
import { shallow } from "enzyme";
import Image from "./Image";
describe("Testing of Image component", () => {
it("render image component with default value", () => {
const wrapper = shallow(<Image />);
expect(wrapper).toBeTruthy();
expect(wrapper.find("img").length).toEqual(1);
});
it("render image component with props ", () => {
const props = {
fileName: "facebook.png",
altName: "facebook"
};
const wrapper = shallow(<Image {...props} />);
expect(wrapper).toBeTruthy();
expect(wrapper.find("img").length).toEqual(1);
});
});
这对我有用...
组件:
function Header() {
return (
<div className="header">
<img src="images/logo.png" alt="no logo found"/>
</div>
)
}
测试:
it('should set logo image src correctly', () => {
const logoImg = mountedHeader.find('img')
expect(logoImg.getElement(0).props.src).toEqual("images/logo.png")
});
describe("CharacterInfo", () => {
const data={
image:"ricky.jpg",
}
it("should renders img src", () => {
const wrapper=shallow(<CharacterInfo image={data.image}/>);
});
const imgSrc= wrapper.find("img").prop('src');
expect(imgSrc).toBe("ricky.jpg");
})