我正在关注此链接以检查如何使用jest来测试React代码: https://facebook.github.io/jest/docs/tutorial-react.html
在我想测试当前组件之前,一切都已找到。 Out组件是这样写的:
followers
这与教程中的javasrcript版本几乎相同,只不过我将其更改为babel格式。现在,如果我使用它:
let React = require('react');
var CheckboxWithLabel = React.createClass({
getInitialState: function() {
return {
isChecked: false
}
},
onChange: function(){
this.setState({isChecked: !this.state.isChecked});
},
render: function(){
return (
<label>
<input
type="checkbox"
checked={this.state.isChecked}
onChange={this.onChange}
/>
{this.state.isChecked ? this.props.labelOn : this.props.labelOff}
</label>
)
}
});
module.exports = CheckboxWithLabel;
我遇到了这个例外:
jest.unmock("../CheckboxWithLabel");
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import CheckboxWithLabel from '../CheckboxWithLabel';
describe('CheckboxWithLabel', ()=>{
it('change the text after click', ()=>{
// Render a checkbox with label in the document
const checkbox = TestUtils.renderIntoDocument(
<CheckboxWithLabel labelOn="On" labelOff="Off" />
);
const checkboxNode = ReactDOM.findDOMNode(checkbox);
// Verify that it's Off by default
expect(checkboxNode.textContent).toEqual('Off');
// Simulate a click and verify that it is now On
TestUtils.Simulate.change(
TestUtils.findRenderedDOMComponentWithTag(checkbox, 'input')
);
expect(checkboxNode.textContent).toEqual('On');
});
});
这是package.json:
Using Jest CLI v12.1.1, jasmine2, babel-jest
FAIL __tests__/checkboxWithLabel-test.js
● Runtime Error
- Error: Cannot find module '../CheckboxWithLabel' from 'checkboxWithLabel-test.js'
at Resolver.resolveModule (node_modules/jest-cli/node_modules/jest-resolve/src/index.js:117:17)
at Object.<anonymous> (__tests__/checkboxWithLabel-test.js:1:162)
和.babelrc是这样的:
{
"dependencies": {
"react": "~0.14.0",
"react-dom": "~0.14.0"
},
"devDependencies": {
"babel-core": "^6.9.0",
"babel-jest": "^9.0.0",
"babel-polyfill": "*",
"babel-preset-es2015": "*",
"babel-preset-react": "*",
"jest-cli": "*",
"react-addons-test-utils": "~0.14.0"
},
"scripts": {
"test": "jest"
},
"jest": {
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/"
]
}
}
因为我们当前的大多数代码都是用.jsx格式编写的,使用对象样式而不是类样式,我怎样才能使用jest?
由于
答案 0 :(得分:3)
您需要在开玩笑选项中进行其他设置:
"jest": {
"moduleFileExtensions": [
"js",
"jsx"
],
}
这将允许jest使用.js和.jsx扩展名测试文件