Pat*_* Lu 8 testing chai reactjs jestjs enzyme
我收到一个错误:Invalid Chai property: toMatchSnapshot
当我尝试使用 Jest + Enzyme 的快照测试时。我已将我的 React 版本更新为 16.2,并且将enzyme-to-json
库与 Enzyme 3 一起使用。
代码如下:
import React from 'react';
import ReactDOM from 'react-dom';
import ConnectedApp, { App } from './App';
import { ConnectedRouter } from 'react-router-redux';
import { Provider } from 'react-redux';
import { expect } from 'chai';
import { mount, shallow } from 'enzyme';
import createHistory from 'history/createMemoryHistory'
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import toJson from 'enzyme-to-json';
describe('App tests', () => {
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
let store, container, history, wrapper;
const initialState = {
output: true
}
beforeEach(() => {
store = mockStore(initialState);
history = createHistory();
wrapper = mount(
<Provider store={store}>
<ConnectedRouter history={history}>
<ConnectedApp />
</ConnectedRouter>
</Provider>
)
});
it('+++capturing Snapshot of App', () => {
expect(toJson(wrapper)).toMatchSnapshot();
});
})
Run Code Online (Sandbox Code Playgroud)
我也用 Jest 的渲染试过这个:
import renderer from 'react-test-renderer';
it('renders correctly', () => {
var component = <Provider store={store}>
<ConnectedRouter history={history}>
<ConnectedApp />
</ConnectedRouter>
</Provider>
const tree = renderer
.create(component)
.toJSON();
expect(tree).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)
但我仍然收到Invalid Chai property: toMatchSnapshot
错误。有谁知道怎么回事?
这不是您使用的渲染器的问题。问题是您使用的是 chai 期望而不是 jest 附带的期望库。chai API 没有toMatchSnapshot
方法。要修复它,您可以执行以下操作:
import { expect } from 'chai'
但是,如果您需要继续使用 chai(即您已经编写了很多 chai 测试并且您不想一次进行大修),您可以做两件事:
expect
在您的测试设置文件中别名 chai 或 jest函数,例如global.chaiExpect = chai.expect
Monkey-patch 全局expect
函数,以便您可以像这篇博文中一样使用 chai 和 jest API:https : //medium.com/@RubenOostinga/combining-chai-and-jest-matchers-d12d1ffd0303
相关位是这样的:
// Make sure chai and jasmine ".not" play nice together
const originalNot = Object.getOwnPropertyDescriptor(chai.Assertion.prototype, 'not').get;
Object.defineProperty(chai.Assertion.prototype, 'not', {
get() {
Object.assign(this, this.assignedNot);
return originalNot.apply(this);
},
set(newNot) {
this.assignedNot = newNot;
return newNot;
},
});
// Combine both jest and chai matchers on expect
const originalExpect = global.expect;
global.expect = (actual) => {
const originalMatchers = originalExpect(actual);
const chaiMatchers = chai.expect(actual);
const combinedMatchers = Object.assign(chaiMatchers, originalMatchers);
return combinedMatchers;
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2899 次 |
最近记录: |