【问题标题】:React unit test: tried to test function's html tag but failReact 单元测试:尝试测试函数的 html 标签但失败
【发布时间】:2018-07-10 03:38:33
【问题描述】:

我在 react 中运行单元测试时遇到了这个错误:

TypeError: setArticleList.find 不是函数

21 |期望(setArticleList.find('div').length >0).to.equal(true);

navList.test.js

describe('NavList', function () {
    const app = shallow(<NavList/>);
    it('function setArticleList() ', function () {
        const setArticleList = app.instance().setArticleList();
        expect(setArticleList.find('div').length >0).to.equal(true);
    });
});

navList.js

setArticleList(){
    return (
        <div className="list-unstyled d-flex align-items-center">
            <div>test</div>
        </div>
    );
}

为什么setArticleList.find 不是函数? 通过了类似以下的内容:

const app = shallow();

expect(app.find('h2').length).to.equal(1);

如果我修改 setArticleList()setArticleList(){return true;}

然后运行 ​​expect(setArticleList).to.equal(true);

也可以通过。

那么为什么我会收到错误消息?

【问题讨论】:

  • 有人帮忙吗?
  • .instance() 只会让您获得对组件中方法的引用,但不会呈现它。您只能在 shallow() 或 mount() 引用上使用 .find() 。您不能在 instance() 上使用 find()。您可能应该将您的 ArticleList 代码放入一个单独的功能组件中并单独测试它,或者您应该在代码中的浅渲染应用变量上找到这个 div。

标签: reactjs unit-testing


【解决方案1】:

你绑定函数了吗? 尝试在主构造函数上绑定函数

this.setArticleList = setArticleList.bind(this);

【讨论】:

  • 您好,感谢您的回复,但似乎不是问题。
猜你喜欢
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 2021-12-15
  • 2018-10-27
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多