我正在尝试制作此组件的快照:
export default class LoginExternalApi extends Component {
constructor(props) {
super(props);
}
render() {
let store = this.props.store.getState();
return (
<View style={styles.container}>
{store.facebookToken ? null : <FacebookButtonConnect />}
{store.spotifyToken ? null : <SpotifyButtonConnect />}
</View>
)
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我在方法中有一个store变量render(),它调用了一个 props。
这是我基于 Jest librairie 的测试文件:
import 'react-native';
import React from 'react';
import LoginExternalApi from '../app/scenes/LoginExternalApi';
import renderer from 'react-test-renderer';
test('LoginExternalApi scene renders correctly', () => {
const tree = renderer.create(
<LoginExternalApi />
).toJSON();
expect(tree).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)
这是我的错误: TypeError: …
我想用Jest和Enzyme测试一个React组件.此组件是一个登录表单,当用户单击登录按钮时,我想根据结果检查对象模型是否相应地更新了对象模型.
以下是用户单击提交按钮时调用的代码部分.
// Login.jsx
handleSubmit(e) {
var that = this;
this.setState({stateResult: "", errorLabel: ""});
if(e) {
e.preventDefault();
e.stopPropagation();
}
MyService.login(this.state.email, this.state.password).then(function(account) {
that.setState({stateResult: "login-ok", errorLabel: ""});
}).catch(function(err) {
that.setState({stateResult: "login-error", errorLabel: err.data.message});
});
};
Run Code Online (Sandbox Code Playgroud)
我写了一个Jest测试.这是代码:
// Login-test.js
test('that when the signin fails, the stateResult model is updated with login-error', () => {
const wrapper = shallow(<Landing />);
wrapper.find('a#landingjsx-signin').simulate('click');
wrapper.update();
setTimeout(function() {
expect(wrapper.state().stateResult).toEqual("login-error");
}, 100);
});
Run Code Online (Sandbox Code Playgroud)
为了测试它,我使用MyService的模拟
jest.mock('../../../modules/MyService.js');
Run Code Online (Sandbox Code Playgroud)
这是我的模拟代码:
//MyService.js
class MyService {
constructor() {
}
login(user, password) {
return new …Run Code Online (Sandbox Code Playgroud) 我正在为模块编写单元测试.我真的需要帮助来处理全球变量和功能.我的问题如下:假设我想测试名为'needTest.js'的模块.结构如下:

因为我只需要在我的测试文件中测试needTest.js中的main函数,我首先import main from '../needTest.js'.而我的问题是:函数main不仅需要三个输入p1,p2和p3,它还取决于一些全局变量或函数,如isA,isB,isC.如何在我的测试文件中模拟这些全局变量?我想简单地替换那些全局变量的返回值,让我的测试文件忽略它导入的内容,但只使用我嘲笑的东西.
我正在为减速机测试工作.但是具有动作功能的减速器的返回状态是异常的.
reducer.react-test.js
import reducer from '../../test_module/reducer';
describe('Test Reducer', () => {
const initStatus = { id: -1, list: [] };
it('1. has default state', () => {
expect(reducer(initStatus, { type: 'unexpected' })).toEqual({
...initStatus
});
});
it('2. has added once', () => {
expect(reducer(initStatus, { type: "ADD" })).toEqual({
...initStatus,
id: 0,
list: [0],
});
});
it('3. has added twice', () => {
const afterAddOnce = reducer(initStatus, { type: "ADD" });
expect(reducer(afterAddOnce, { type: "ADD" })).toEqual({
...initStatus,
id: 1,
list: [0,1],
}); …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Jest在我的react/react-native库上运行一些测试(内部只有一些业务逻辑).
我们正在测试使用fetch函数的操作(使用whatwg-fetch进行polyfill).我添加了whatwg-fetch(感谢Safari)的反应.
每当我尝试运行测试时,我都会收到此错误:
TypeError: Cannot read property 'fetch' of undefined
at node_modules/whatwg-fetch/fetch.js:4:11
at Object.<anonymous> (node_modules/whatwg-fetch/fetch.js:461:3)
at Object.<anonymous> (node_modules/jest-expo/src/setup.js:138:416)
Run Code Online (Sandbox Code Playgroud)
什么可能导致这个问题?在jest配置中有没有办法避免这种情况?
以下是一些用于调试的文件:
在package.json中进行Jest配置
"jest": {
"preset": "jest-expo",
"moduleFileExtensions": [
"js",
"jsx",
"ts",
"tsx"
],
"verbose": true,
"transform": {
"^.+\\.(js|ts|tsx)$": "<rootDir>/node_modules/babel-jest"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/",
"<rootDir>/dist/"
],
"transformIgnorePatterns": [
"node_modules/?!react-native"
]
},
Run Code Online (Sandbox Code Playgroud)
Webpack配置:
const config = {
entry: [
'whatwg-fetch',
__dirname + '/src/index.ts',
],
devtool: 'source-map',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.js',
library: 'checkinatwork-module',
libraryTarget: 'umd',
umdNamedDefine: true,
}, …Run Code Online (Sandbox Code Playgroud) 我用jest.fn模拟了两个函数:
let first = jest.fn();
let second = jest.fn();
Run Code Online (Sandbox Code Playgroud)
我如何断言first之前调用过second?
我正在寻找类似于sinon的 .calledBefore断言。
更新 我使用了这种简单的“临时”解决方法
it( 'should run all provided function in order', () => {
// we are using this as simple solution
// and asked this question here /sf/ask/3224637531/
let excutionOrders = [];
let processingFn1 = jest.fn( () => excutionOrders.push( 1 ) );
let processingFn2 = jest.fn( () => excutionOrders.push( 2 ) );
let processingFn3 = jest.fn( () => excutionOrders.push( 3 ) ); …Run Code Online (Sandbox Code Playgroud) 我在package.json文件中有一个npm任务,如下所示执行jest测试:
"scripts": {
"test-jest": "jest",
"jest-coverage": "jest --coverage"
},
"jest": {
"testEnvironment": "jsdom"
},
Run Code Online (Sandbox Code Playgroud)
我想npm run test-jest用grunt 执行这个任务.我为此安装了grunt-run并添加了运行任务,但是如何在那里调用这个npm任务呢?
run: {
options: {
// Task-specific options go here.
},
your_target: {
cmd: 'node'
}
}
Run Code Online (Sandbox Code Playgroud) 我想用changedSince和onlyChanged标志开玩笑。我更改了许多测试以及测试所依赖的文件。根据 jest cli 标志的文档:
changedSince:运行与自提供分支以来的更改相关的测试。如果当前分支与给定分支有分歧,则只会测试本地所做的更改。
onlyChanged : 别名 -o。尝试根据当前存储库中已更改的文件来确定要运行的测试。仅当您目前在 git/hg 存储库中运行测试并且需要静态依赖关系图(即没有动态需要)时才有效。
但是当我运行jest --changedSince=master或jest --onlyChanged它运行 0 个测试时,根本没有在终端中提供任何内容。
jest --listTests列出所有测试。但是,当我运行jest --listTests --changedSince=masteror 时jest --listTests --onlyChanged,它没有列出任何测试。
我将测试使用 Jest 运行的后端服务器。有时会成功,但有时会显示这样的错误。

因此,如果我按照建议使用 --detectOpenHandles 标志,它总是成功而不显示任何错误。这是测试代码。
it("should be able to initialize a server (development)",async (done) => {
// Before main() is called there is no active connection:
expect(connection.readyState).toBe(0);
return main({
env: "dev",
port: PORT,
})
.then(async (server: ApolloServer) => {
// After main() got called, there is an active connection:
expect(connection.readyState).toBe(1);
await server.stop();
done();
})
});
afterAll(async () => {
await connection.close(); //connection is mongoose.connection
});
Run Code Online (Sandbox Code Playgroud)
我不知道为什么它在标记时失败。奇怪的是,有时成功,有时失败。
谢谢
我用Jest / Enzyme编写的测试用例遇到了麻烦。我有一个React / Redux组件,正在尝试编写一个基本测试,但是得到以下错误:
Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was 'undefined'.
这是我的代码:
dashboardComponent.js
import '../stylesheets/dashboardComponent.css';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as dashboardActions from '../actions/dashboardActions';
class DashboardComponent extends Component {
constructor(props) {
super();
}
componentDidMount() {
this.props.actions.getDashboardContent();
}
render() {
return (
< SOME JSX HERE >
);
}
}
function mapStateToProps(state) { …Run Code Online (Sandbox Code Playgroud) jestjs ×10
reactjs ×7
javascript ×3
unit-testing ×3
redux ×2
testing ×2
apollo ×1
babel-jest ×1
enzyme ×1
fetch ×1
git ×1
graphql ×1
gruntjs ×1
node.js ×1
npm ×1
promise ×1
react-native ×1
snapshot ×1
webpack ×1