샘플
got 11.8.6: post
검증된 샘플 — npm got 11.8.6: post. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: got.post is a callable function on the got object
sha256:196c1be92a727c66c117881e66d7c6a829d52434dfa2aae81a8fd03ee739e76d
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2… |
2026-09-05 |
케이스
HOW- 목표
- verify got.post in pkg:npm/got@11.8.6
- 패키지
- 심벌
-
- got.post
- 환경
- node 22.23.2
- 생성일
- 2026-09-05T23:20:33Z
컨트랙트
- got.post is a callable function on the got object
- got.post returns a cancelable request promise with .json helper
- got.post throws got.RequestError when mutually exclusive body options are specified
- got.post throws got.RequestError when invalid body type is provided
- got.post sends POST request with serialized JSON payload and parses JSON response
- got.post sends application/x-www-form-urlencoded payload when form option is used
- got.post sends raw string body when body option is used
- got.post includes custom headers in the HTTP request
- got.post throws got.HTTPError on non-2xx HTTP responses
- postJson helper sends JSON payload and receives parsed response
- postForm helper sends form urlencoded payload
- postText helper sends raw text payload
파일
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
소스
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify got.post in pkg:npm/got@11.8.6
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/got@11.8.6
Demonstrate these symbols/APIs:
- got.post
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:e204fd6fa9bd0d76ca50f69895a95a1381152190bf261bd7353eb411cce29a66","contract":["got.post is a callable function on the got object","got.post returns a cancelable request promise with .json helper","got.post throws got.RequestError when mutually exclusive body options are specified","got.post throws got.RequestError when invalid body type is provided","got.post sends POST request with serialized JSON payload and parses JSON response","got.post sends application/x-www-form-urlencoded payload when form option is used","got.post sends raw string body when body option is used","got.post includes custom headers in the HTTP request","got.post throws got.HTTPError on non-2xx HTTP responses","postJson helper sends JSON payload and receives parsed response","postForm helper sends form urlencoded payload","postText helper sends raw text payload"],"goal":"verify got.post in pkg:npm/got@11.8.6","kind":"HOW","packages":["pkg:npm/got@11.8.6"],"schemaVersion":1,"symbols":["got.post"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/got@11.8.6"],"schemaVersion":1,"subject":"pkg:npm/got@11.8.6","symbols":["got.post"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-got-post",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-got-post",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"got": "11.8.6"
}
},
"node_modules/@sindresorhus/is": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",
"integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sindresorhus/is?sponsor=1"
}
},
"node_modules/@szmarczak/http-timer": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",
"integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",
"license": "MIT",
"dependencies": {
"defer-to-connect": "^2.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/@types/cacheable-request": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",
"integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==",
"license": "MIT",
"dependencies": {
"@types/http-cache-semantics": "*",
"@types/keyv": "^3.1.4",
"@types/node": "*",
"@types/responselike": "^1.0.0"
}
},
"node_modules/@types/http-cache-semantics": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
"integrity": "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==",
"license": "MIT"
},
"node_modules/@types/keyv": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",
"integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/node": {
"version": "26.4.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.1.tgz",
"integrity": "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/@types/responselike": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz",
"integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/cacheable-lookup": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",
"integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",
"license": "MIT",
"engines": {
"node": ">=10.6.0"
}
},
"node_modules/cacheable-request": {
"version": "7.0.4",
"resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",
"integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",
"license": "MIT",
"dependencies": {
"clone-response": "^1.0.2",
"get-stream": "^5.1.0",
"http-cache-semantics": "^4.0.0",
"keyv": "^4.0.0",
"lowercase-keys": "^2.0.0",
"normalize-url": "^6.0.1",
"responselike": "^2.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/clone-response": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",
"integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",
"license": "MIT",
"dependencies": {
"mimic-response": "^1.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/decompress-response": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
"license": "MIT",
"dependencies": {
"mimic-response": "^3.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/decompress-response/node_modules/mimic-response": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/defer-to-connect": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",
"integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
"license": "MIT",
"dependencies": {
"once": "^1.4.0"
}
},
"node_modules/get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
"integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
"license": "MIT",
"dependencies": {
"pump": "^3.0.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/got": {
"version": "11.8.6",
"resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz",
"integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==",
"license": "MIT",
"dependencies": {
"@sindresorhus/is": "^4.0.0",
"@szmarczak/http-timer": "^4.0.5",
"@types/cacheable-request": "^6.0.1",
"@types/responselike": "^1.0.0",
"cacheable-lookup": "^5.0.3",
"cacheable-request": "^7.0.2",
"decompress-response": "^6.0.0",
"http2-wrapper": "^1.0.0-beta.5.2",
"lowercase-keys": "^2.0.0",
"p-cancelable": "^2.0.0",
"responselike": "^2.0.0"
},
"engines": {
"node": ">=10.19.0"
},
"funding": {
"url": "https://github.com/sindresorhus/got?sponsor=1"
}
},
"node_modules/http-cache-semantics": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
"integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",
"license": "BSD-2-Clause"
},
"node_modules/http2-wrapper": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz",
"integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==",
"license": "MIT",
"dependencies": {
"quick-lru": "^5.1.1",
"resolve-alpn": "^1.0.0"
},
"engines": {
"node": ">=10.19.0"
}
},
"node_modules/json-buffer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
"integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
"license": "MIT"
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
"integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
"license": "MIT",
"dependencies": {
"json-buffer": "3.0.1"
}
},
"node_modules/lowercase-keys": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
"integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/mimic-response": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",
"integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/normalize-url": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",
"integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/p-cancelable": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
"integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/pump": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
"license": "MIT",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"node_modules/quick-lru": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
"integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/resolve-alpn": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",
"integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==",
"license": "MIT"
},
"node_modules/responselike": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",
"integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",
"license": "MIT",
"dependencies": {
"lowercase-keys": "^2.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"license": "MIT"
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
}
}
}
{
"name": "sample-got-post",
"version": "1.0.0",
"type": "module",
"private": true,
"license": "MIT-0",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"got": "11.8.6"
}
}
{
"schemaVersion": 1,
"goal": "verify got.post in pkg:npm/got@11.8.6",
"kind": "HOW",
"packages": [
"pkg:npm/got@11.8.6"
],
"symbols": [
"got.post"
]
}
import got from 'got';
/**
* Sends an HTTP POST request with a JSON payload and expects a JSON response.
* @param {string|URL} url Target URL or path relative to prefixUrl.
* @param {unknown} data JSON-serializable payload.
* @param {object} [options={}] Additional Got options.
* @returns {import('got').CancelableRequest<import('got').Response<unknown>>}
*/
export function postJson(url, data, options = {}) {
return got.post(url, {
...options,
json: data,
responseType: 'json'
});
}
/**
* Sends an HTTP POST request with form-encoded data (application/x-www-form-urlencoded).
* @param {string|URL} url Target URL or path relative to prefixUrl.
* @param {Record<string, unknown>} formData Key-value form fields.
* @param {object} [options={}] Additional Got options.
* @returns {import('got').CancelableRequest<import('got').Response<string>>}
*/
export function postForm(url, formData, options = {}) {
return got.post(url, {
...options,
form: formData
});
}
/**
* Sends an HTTP POST request with raw text or buffer body.
* @param {string|URL} url Target URL or path relative to prefixUrl.
* @param {string|Buffer} body Raw payload body.
* @param {object} [options={}] Additional Got options.
* @returns {import('got').CancelableRequest<import('got').Response<string>>}
*/
export function postText(url, body, options = {}) {
return got.post(url, {
...options,
body
});
}
export { got };
export default got;
import assert from 'node:assert/strict';
import http from 'node:http';
import got, { postJson, postForm, postText } from '../src/index.mjs';
// 1. got.post is a callable function on the got object
{
assert.equal(typeof got.post, 'function', 'got.post should be a function');
}
// 2. got.post returns a cancelable request promise with .json helper
{
const req = got.post('http://127.0.0.1:0', { body: 'test' });
req.catch(() => {}); // prevent unhandled rejection
assert.equal(typeof req.then, 'function', 'return value should be thenable');
assert.equal(typeof req.json, 'function', 'return value should have .json() method');
assert.equal(typeof req.cancel, 'function', 'return value should have .cancel() method');
}
// 3. got.post throws got.RequestError when mutually exclusive body options are specified
{
await assert.rejects(
async () => {
await got.post('http://127.0.0.1:0', {
json: { key: 'val' },
form: { key: 'val' }
});
},
(err) => {
assert(err instanceof got.RequestError, 'Should throw got.RequestError');
assert.match(err.message, /mutually exclusive/i);
return true;
}
);
}
// 4. got.post throws got.RequestError when invalid body type is provided
{
await assert.rejects(
async () => {
await got.post('http://127.0.0.1:0', {
body: 12345
});
},
(err) => {
assert(err instanceof got.RequestError, 'Should throw got.RequestError');
assert.match(err.message, /must be a stream\.Readable, string or Buffer/i);
return true;
}
);
}
// Set up offline local HTTP server to verify network behaviors
const recordedRequests = [];
const server = http.createServer(async (req, res) => {
let body = '';
for await (const chunk of req) {
body += chunk;
}
recordedRequests.push({
method: req.method,
url: req.url,
headers: req.headers,
body
});
if (req.url === '/json') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: JSON.parse(body), status: 'ok' }));
} else if (req.url === '/form') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`echo: ${body}`);
} else if (req.url === '/text') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`echo: ${body}`);
} else if (req.url === '/error') {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'bad_request' }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
const baseUrl = `http://127.0.0.1:${port}`;
try {
// 5. got.post sends POST request with serialized JSON payload and parses JSON response
{
const payload = { title: 'Test Post', count: 42 };
const response = await got.post(`${baseUrl}/json`, {
json: payload,
responseType: 'json'
});
assert.equal(response.statusCode, 200);
assert.deepEqual(response.body, { received: payload, status: 'ok' });
const lastReq = recordedRequests[recordedRequests.length - 1];
assert.equal(lastReq.method, 'POST');
assert.match(lastReq.headers['content-type'], /^application\/json/);
assert.deepEqual(JSON.parse(lastReq.body), payload);
}
// 6. got.post sends application/x-www-form-urlencoded payload when form option is used
{
const formFields = { user: 'alice', action: 'login' };
const response = await got.post(`${baseUrl}/form`, {
form: formFields
});
assert.equal(response.statusCode, 200);
assert.equal(response.body, 'echo: user=alice&action=login');
const lastReq = recordedRequests[recordedRequests.length - 1];
assert.equal(lastReq.method, 'POST');
assert.match(lastReq.headers['content-type'], /^application\/x-www-form-urlencoded/);
}
// 7. got.post sends raw string body when body option is used
{
const rawText = 'raw payload content';
const response = await got.post(`${baseUrl}/text`, {
body: rawText,
headers: {
'content-type': 'text/plain'
}
});
assert.equal(response.statusCode, 200);
assert.equal(response.body, 'echo: raw payload content');
const lastReq = recordedRequests[recordedRequests.length - 1];
assert.equal(lastReq.method, 'POST');
assert.equal(lastReq.body, rawText);
}
// 8. got.post includes custom headers in the HTTP request
{
await got.post(`${baseUrl}/text`, {
body: 'ping',
headers: {
'x-custom-header': 'custom-value',
'x-request-id': 'req-98765'
}
});
const lastReq = recordedRequests[recordedRequests.length - 1];
assert.equal(lastReq.headers['x-custom-header'], 'custom-value');
assert.equal(lastReq.headers['x-request-id'], 'req-98765');
}
// 9. got.post throws got.HTTPError on non-2xx HTTP responses
{
await assert.rejects(
async () => {
await got.post(`${baseUrl}/error`, {
json: { test: true }
});
},
(err) => {
assert(err instanceof got.HTTPError, 'Error should be an instance of got.HTTPError');
assert.equal(err.response.statusCode, 400);
return true;
}
);
}
// 10. postJson helper sends JSON payload and receives parsed response
{
const payload = { helper: 'json' };
const response = await postJson(`${baseUrl}/json`, payload);
assert.equal(response.statusCode, 200);
assert.deepEqual(response.body, { received: payload, status: 'ok' });
}
// 11. postForm helper sends form urlencoded payload
{
const response = await postForm(`${baseUrl}/form`, { foo: 'bar' });
assert.equal(response.statusCode, 200);
assert.equal(response.body, 'echo: foo=bar');
}
// 12. postText helper sends raw text payload
{
const response = await postText(`${baseUrl}/text`, 'helper text');
assert.equal(response.statusCode, 200);
assert.equal(response.body, 'echo: helper text');
}
} finally {
server.close();
}
console.log('Contract tests passed successfully.');
오리진 시더
익명