gpt4 book ai didi

unit-testing - 如何对 React-Redux 连接的组件进行单元测试?

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

我使用 Mocha、Chai、Karma、Sinon、Webpack 进行单元测试。

我点击此链接为 React-Redux 代码配置测试环境。

How to implement testing + code coverage on React with Karma, Babel, and Webpack

我可以成功测试我的操作和 reducer JavaScript 代码,但是当测试我的组件时它总是会抛出一些错误。

import React from 'react';
import TestUtils from 'react/lib/ReactTestUtils'; //I like using the Test Utils, but you can just use the DOM API instead.
import chai from 'chai';
// import sinon from 'sinon';
import spies from 'chai-spies';

chai.use(spies);

let should = chai.should()
, expect = chai.expect;

import { PhoneVerification } from '../PhoneVerification';

let fakeStore = {
'isFetching': false,
'usernameSettings': {
'errors': {},
'username': 'sahil',
'isEditable': false
},
'emailSettings': {
'email': 'test@test.com',
'isEmailVerified': false,
'isEditable': false
},
'passwordSettings': {
'errors': {},
'password': 'showsomestarz',
'isEditable': false
},
'phoneSettings': {
'isEditable': false,
'errors': {},
'otp': null,
'isOTPSent': false,
'isOTPReSent': false,
'isShowMissedCallNumber': false,
'isShowMissedCallVerificationLink': false,
'missedCallNumber': null,
'timeLeftToVerify': null,
'_verifiedNumber': null,
'timers': [],
'phone': '',
'isPhoneVerified': false
}
}

function setup () {
console.log(PhoneVerification);
// PhoneVerification.componentDidMount = chai.spy();
let output = TestUtils.renderIntoDocument(<PhoneVerification {...fakeStore}/>);
return {
output
}
}

describe('PhoneVerificationComponent', () => {
it('should render properly', (done) => {
const { output } = setup();
expect(PhoneVerification.prototype.componentDidMount).to.have.been.called;
done();
})
});

上面的代码出现以下错误。

FAILED TESTS:
PhoneVerificationComponent
✖ should render properly
Chrome 48.0.2564 (Mac OS X 10.11.3)
Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

尝试从 sinon spy 切换到 chai-spies。

我应该如何对我的 React-Redux 连接组件(智能组件)进行单元测试?

最佳答案

一种更漂亮的方法是导出普通组件和包含在 connect 中的组件。命名的导出将是组件,默认是包装的组件:

export class Sample extends Component {

render() {
let { verification } = this.props;
return (
<h3>This is my awesome component.</h3>
);
}

}

const select = (state) => {
return {
verification: state.verification
}
}

export default connect(select)(Sample);

通过这种方式,您可以在应用中正常导入,但在测试时,您可以使用 import { Sample } from 'component' 导入命名导出。

关于unit-testing - 如何对 React-Redux 连接的组件进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35131312/

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