Сложная часть состоит в том, как установить значение макета на window.location.search
.
Например index.ts
:
export function main() {
console.log(window.location.search);
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('productId');
}
index.test.ts
:
import { main } from './';
describe('60959971', () => {
it('should pass', () => {
const location = {
...window.location,
search: '?productId=1234',
};
Object.defineProperty(window, 'location', {
writable: true,
value: location,
});
const actual = main();
expect(actual).toBe('1234');
});
});
Результаты модульного тестирования со 100% покрытием:
PASS stackoverflow/60959971/index.test.ts (12.89s)
60959971
✓ should pass (34ms)
console.log stackoverflow/60959971/index.ts:129
?productId=1234
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.136s