1 回答

TA貢獻1810條經(jīng)驗 獲得超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');
});
});
});
單元測試結(jié)果:
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
添加回答
舉報