我正在扩展类中的库函数并更新方法。但我无法编写单元测试用例。这是我的JS文件的组件。在实例化期间,我提供了一个表和一个函数的引用来分派更新redux-store的操作并反映这些更改。
自定义Table.js
import {Table} from 'third-partyLibrary';
const vendorMatch = (typeof Element !== 'undefined'
&& (Element.prototype.matches || Element.prototype.matchesSelector
|| Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector));
function matches(el, query) {
if (vendorMatch) return vendorMatch.call(el, query);
let nodes = el.parentNode ? el.parentNode.querySelectorAll(query) : [];
for (let i = 0; i < nodes.length; i++) {
if (nodes[i] === el) return true;
}
return false;
}
function getParent(_parent, query, _limitEl) {
let limitEl = _limitEl instanceof Array ? _limitEl : [_limitEl || document.body];
let parent = _parent;
while (parent) {
if (matches(parent, query)) {
return parent;
}
if (limitEl.indexOf(parent) !== -1) {
return false;
}
parent = parent.parentNode;
}
return false;
}
class CustomizedTable extends Table {
constructor(el, onRowClick = (code) => {
return code;
}, extraParams = {}) {
super(el, extraParams);
this._onRowClick = onRowClick;
}
_onClick(...args) {
const [e] = args;
if (e.target.type === 'button' || e.target.parentElement.type === 'button') {
return;
}
const target = getParent(e.target || e.srcElement, 'tbody tr', this.el);
const activeRows = this.getActiveRows();
super._onClick(...args);
if (activeRows.length) {
this._onRowClick(activeRows[0].dataset.timezoneCode, false);
}
if (target.dataset) {
this._onRowClick(target.dataset.timezoneCode, true);
}
}
}
export default CustomizedTable;
这就是我想要的:(
import React from 'react';
import {mount} from 'enzyme';
import CustomizedTable from './CustomizedTable';
jest.mock('third-party/js/table');
describe('Cutom Table', () => {
const onRowClick = jest.fn();
const el = (document.body.innerHTML = "<table> <tbody> " +
"<tr data-timezone-code='PO01' className='timeZone'> " +
"<td className='code'>PO01</td>" +
" <td className='description'><span title='VATICAN CITY'>VATICAN CITY</span></td> " +
"<td className='offset'><span title='GMT -1:0'>GMT -1:0</span></td> " +
"<td className='actions' /> " +
"</tr> " +
"</tbody> " +
"</table>");
const extraParams = {};
let TimeZone = new CustomizedTable(el, onRowClick, extraParams);
it('Should Render Table', () => {
const wrapper = mount(<TimeZone/>);
const row = wrapper.find('.timezone');
expect(row.exists()).toBe(true);
expect(row.length).toBe(1);
wrapper.simulate('click');
expect(onRowClick).toHaveBeenCalled();