使用酶的浅渲染:实际和预期的输出不匹配

问题描述 投票:0回答:1

我只是在一个个人项目上编写代码以供学习。

我有一个定义如下的类:

import React from 'react';
export default class Counter{
    counterValue = 0;


    update(newValue){
        this.counterValue = newValue;
    }

    getValue(){
        return this.counterValue;
    }

    displayValue(){
        return <div>{this.getValue()}</div>
    }

}

我正在尝试在displayValue()函数上创建测试。代码如下:

import React from "react";
import Counter from "./Counter";
import Adapter from "enzyme-adapter-react-16";
import { shallow, mount, render, configure } from "enzyme";

configure({ adapter: new Adapter() });
var c1 = new Counter();
c1.update(188);

describe("check displayValue() method", () => {
  it("renders a div", () => {
    const wrapper = shallow(c1.displayValue());
    expect(wrapper.contains(<div>188</div>)).toBe(true);
  });
});

我使用了命令npm test,并执行了“反应脚本测试”。

测试失败。它告诉我

expect(received).toBe(expected) // Object.is equality

Expected: true
Received: false

并且错误归因于此行:

expect(wrapper.contains(<div>188</div>)).toBe(true);

我在理解这一点时遇到困难,不胜感激。谢谢!

javascript reactjs enzyme
1个回答
1
投票

您需要在数字上加上{}:

import React from "react";
import Counter from "./Counter";
import Adapter from "enzyme-adapter-react-16";
import { shallow, mount, render, configure } from "enzyme";

configure({ adapter: new Adapter() });
var c1 = new Counter();
c1.update(188);

describe("check displayValue() method", () => {
  it("renders a div", () => {
    const wrapper = shallow(c1.displayValue());
    expect(wrapper.contains(<div>{188}</div>)).toBe(true);
  });
});

有关更多详细信息,请检查here

© www.soinside.com 2019 - 2024. All rights reserved.