我对单元测试非常陌生,并且正在尝试通过我的 react-redux 项目来编写一些测试。
为什么这个测试不起作用,我怎样才能让它通过?
这是测试。我想测试我的获取帖子操作创建者。这是一个小型博客应用程序。:
import configureStore from 'redux-mock-store'; // ES6 modules
import { findSinglePost, sendEdit, changeRedirect, checkBoxChange } from '../client/redux/actions/postActions';
import thunk from 'redux-thunk';
import axios from 'axios';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('asynchronous action creators', () => {
it('should fetch posts', () => {
let store = mockStore({})
//my async action creator. It uses mock data that's in the same folder.
const fetchPosts = () => function(dispatch) {
dispatch({type: 'FETCH_POSTS'});
return axios.get('./MOCK.json').then((response) => {
dispatch({type: 'FETCH_POSTS_FUFILLED', payload: response.data});
}).catch((err) => {
dispatch({type: 'FETCH_POSTS_REJECTED', payload: err});
});
};
//this doesn't equal FETCH_POSTS_FUFILLED, it ends up equaling just "FETCH_POSTS"
return store.dispatch(fetchPosts()).then(() => {
const actions = store.getActions();
expect(actions[0]).toEqual({type: 'FETCH_POSTS_FUFILLED'});
})
})
});
这是 jest 的反馈。我希望它等于'FETCH_POSTS_'FUFILLED',但它返回'FETCH_POSTS'。:
FAIL _test_\actions.test.js
● asynchronous action creators › should fetch posts
expect(received).toEqual(expected)
Expected value to equal:
{"type": "FETCH_POSTS_FUFILLED"}
Received:
{"type": "FETCH_POSTS"}
Difference:
- Expected
+ Received
Object {
- "type": "FETCH_POSTS_FUFILLED",
+ "type": "FETCH_POSTS",
}
88 | return store.dispatch(fetchPosts()).then(() => {
89 | const actions = store.getActions();
> 90 | expect(actions[0]).toEqual({type: 'FETCH_POSTS_FUFILLED'});
91 | })
92 | })
93 | });
at _test_/actions.test.js:90:26
PASS client\views\LoginPage\LoginPage.test.jsx
Test Suites: 1 failed, 1 passed, 2 total
Tests: 1 failed, 5 passed, 6 total
Snapshots: 0 total
Time: 1.49s
Ran all test suites related to changed files.
此外,如果您想尝试运行它,这里是项目的 github 存储库。
此外,如果业内有一种更广为人知的标准方法,我会喜欢这个建议。
编辑:
当我将操作 [0] 更改为操作 [1]时,我收到此错误:
Expected value to equal:
{"type": "FETCH_POSTS_FUFILLED"}
Received:
{"payload": {Symbol(impl): {"message": "The string did not match the expected pattern.", "name": "SyntaxError", Symbol(wrapper): [Circular]}}, "type": "FETCH_POSTS_REJECTED"}
Difference:
- Expected
+ Received
Object {
- "type": "FETCH_POSTS_FUFILLED",
+ "payload": DOMException {
+ Symbol(impl): DOMExceptionImpl {
+ "message": "The string did not match the expected pattern.",
+ "name": "SyntaxError",
+ Symbol(wrapper): [Circular],
+ },
+ },
+ "type": "FETCH_POSTS_REJECTED",