Jest + Enzyme:如何测试图像 src? [英] Jest + Enzyme: How to test an image src?

查看:23
本文介绍了Jest + Enzyme:如何测试图像 src?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个徽标组件:

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");
  });
});

但是当我运行测试时,出现了一些奇怪的错误:

But when I run the test, there is some weird error:

$ 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"?

How am I supposed to test that the image src === "assets/images/logo.png"?

推荐答案

我想您在 Logo components 附近的 __test__ 目录中编写测试.

I suppose that you write your tests inside a __test__ directory near Logo components .

无论如何,导入您的assets/images/logo.png";相对于您的测试文件.

Anyway, import your "assets/images/logo.png" relatively to your test file.

如果你的项目结构是这样的

if your project structure is like this

Project
├── assets 
│   └── images
├       |
│       └── logo.png
├── src 
│   └── components
├       |── Logo.js 
│       └── __tests__
├           └── logo.test.js 
└ 

首先,就像我说的,通过键入将图像导入到您的 logo.test.js 中:

First, Like I said import image into your logo.test.js by typing:

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);

     });
 });

这篇关于Jest + Enzyme:如何测试图像 src?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆