gpt4 book ai didi

unit-testing - React.js 和 Jasmine Spies

转载 作者:行者123 更新时间:2023-12-03 14:28:20 24 4
gpt4 key购买 nike

使用基本的 test-utils 和 jasmine 进行单元测试。

如何监视 React 组件内的函数?

测试.js:

class Test extends React.Component {
handleClick() {
// Do something
}

render() {
return (
<div className="test-class" onClick={this.handleClick}>Test</div>
);
}
}

const React = require('react-with-addons');
const RequireJsTest = require('requirejs-test');
const Utils = React.addons.TestUtils;
const Test = require('./test');

describe('test', () => {
it('should test', function() {
const test = Utils.renderIntoDocument(<Test/>);
const el = Utils.findRenderedDOMComponentWithClass(test, 'test-class');
spyOn(test, 'handleClick');
Utils.Simulate.click(el);

expect(test.handleClick).toHaveBeenCalled();
});
});

我收到以下错误:

Expected spy handleClick to have been called. (1)

有什么想法吗?谢谢!

最佳答案

说实话,我还没有测试过 React 应用程序,但是试试 method (描述 block 中的最后一个测试),我刚刚在enzyme中找到了它自述文件。

我认为你应该在渲染组件之前监视组件类原型(prototype)方法:

spyOn(Test.prototype, 'handleClick');
// and then
expect(Test.prototype.handleClick).toHaveBeenCalled();

关于unit-testing - React.js 和 Jasmine Spies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com