1 回答
TA贡献1810条经验 获得超4个赞
只需使用Object.defineProperty()直接在window对象上定义属性。
例如
index.js:
const setEnterpriseCookie = (...args) => {
let path = window.location.pathname;
if (path.match(/.*\/enterprise.*/)) {
window.TOOL.cookie.setCookie(...args);
}
};
exports.setEnterpriseCookie = setEnterpriseCookie;
index.test.js:
const { setEnterpriseCookie } = require('./');
describe('63274598', () => {
describe('Tests for the page-specific-methods.js file', () => {
test('Test the page path detecting the enterprise string', () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/enterprise/contact' },
});
Object.defineProperty(window, 'TOOL', {
value: {
cookie: {
setCookie: jest.fn(),
},
},
});
setEnterpriseCookie('123');
expect(window.TOOL.cookie.setCookie).toBeCalledTimes(1);
expect(window.TOOL.cookie.setCookie).toHaveBeenLastCalledWith('123');
});
});
});
单元测试结果:
PASS stackoverflow/63274598/index.test.js (13.923s)
63274598
Tests for the page-specific-methods.js file
✓ Test the page path detecting the enterprise string (4ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 50 | 100 | 100 |
index.js | 100 | 50 | 100 | 100 | 3
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.975s
添加回答
举报