jest-matcher-http 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.editorconfig ADDED
@@ -0,0 +1,12 @@
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ indent_size = 2
6
+ end_of_line = lf
7
+ charset = utf-8
8
+ trim_trailing_whitespace = true
9
+ insert_final_newline = true
10
+
11
+ [*.md]
12
+ trim_trailing_whitespace = false
package/.eslintrc.js ADDED
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ module.exports = {
4
+ env: {
5
+ node: true,
6
+ 'jest/globals': true,
7
+ },
8
+ extends: [
9
+ 'airbnb-base',
10
+ 'plugin:jsdoc/recommended',
11
+ 'plugin:jest/recommended',
12
+ 'plugin:jest/style',
13
+ ],
14
+ plugins: ['jest'],
15
+ overrides: [],
16
+ parserOptions: {
17
+ ecmaVersion: 2020,
18
+ sourceType: 'script', // https://github.com/eslint/eslint/issues/5301#issuecomment-184720161
19
+ },
20
+ rules: {
21
+ strict: ['error', 'global'], // Needed: https://github.com/airbnb/javascript/issues/722
22
+ 'jsdoc/check-types': 'error',
23
+ 'jsdoc/check-property-names': 'error',
24
+ 'jsdoc/check-param-names': 'error',
25
+ 'jsdoc/check-tag-names': 'error',
26
+ 'jsdoc/check-alignment': 'error',
27
+ 'jsdoc/check-indentation': 'error',
28
+ 'jsdoc/empty-tags': 'error',
29
+ 'jsdoc/newline-after-description': 'error',
30
+ 'jsdoc/require-description-complete-sentence': [
31
+ 'error',
32
+ { abbreviations: ['etc', 'e.g.', 'i.e.'] },
33
+ ],
34
+ 'jsdoc/require-description': 'error',
35
+ 'jsdoc/require-hyphen-before-param-description': 'error',
36
+ 'jsdoc/require-jsdoc': 'error',
37
+ 'jsdoc/require-param-description': 'error',
38
+ 'jsdoc/require-param-name': 'error',
39
+ 'jsdoc/require-param-type': 'error',
40
+ 'jsdoc/require-param': 'error',
41
+ 'jsdoc/require-property': 'error',
42
+ 'jsdoc/require-property-description': 'error',
43
+ 'jsdoc/require-property-name': 'error',
44
+ 'jsdoc/require-property-type': 'error',
45
+ 'jsdoc/require-returns-check': 'error',
46
+ 'jsdoc/require-returns-description': 'error',
47
+ 'jsdoc/require-returns-type': 'error',
48
+ 'jsdoc/require-returns': 'error',
49
+ 'jsdoc/valid-types': 'error',
50
+ 'jest/consistent-test-it': 'error',
51
+ 'jest/expect-expect': 'error',
52
+ 'jest/prefer-lowercase-title': 'error',
53
+ 'jest/no-alias-methods': 'error',
54
+ 'jest/no-commented-out-tests': 'error',
55
+ 'jest/no-conditional-expect': 'error',
56
+ 'jest/no-disabled-tests': 'error',
57
+ 'jest/no-duplicate-hooks': 'error',
58
+ 'jest/no-export': 'error',
59
+ 'jest/no-focused-tests': 'error',
60
+ 'jest/no-identical-title': 'error',
61
+ 'jest/no-if': 'error',
62
+ 'jest/no-jasmine-globals': 'error',
63
+ 'jest/no-mocks-import': 'error',
64
+ 'jest/no-restricted-matchers': 'error',
65
+ 'jest/no-standalone-expect': 'error',
66
+ 'jest/no-test-return-statement': 'error',
67
+ 'jest/prefer-called-with': 'error',
68
+ 'jest/prefer-hooks-on-top': 'error',
69
+ 'jest/prefer-spy-on': 'error',
70
+ 'jest/prefer-strict-equal': 'error',
71
+ 'jest/prefer-to-be': 'error',
72
+ 'jest/prefer-to-contain': 'error',
73
+ 'jest/prefer-to-have-length': 'error',
74
+ 'jest/prefer-todo': 'error',
75
+ 'jest/require-top-level-describe': 'error',
76
+ 'jest/require-to-throw-message': 'error',
77
+ 'jest/valid-describe-callback': 'error',
78
+ 'jest/valid-expect-in-promise': 'error',
79
+ 'jest/valid-expect': 'error',
80
+ 'jest/valid-title': 'error',
81
+ quotes: [2, 'single', { avoidEscape: true }],
82
+ 'comma-dangle': [2, 'always-multiline'],
83
+ },
84
+ };
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+
3
+ .git-hooks/pre-commit-eslint
4
+ .git-hooks/pre-commit-test-unit
@@ -0,0 +1,36 @@
1
+ #!/bin/sh
2
+
3
+ STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".jsx\{0,1\}$")
4
+
5
+ if [[ "$STAGED_FILES" = "" ]]; then
6
+ exit 0
7
+ fi
8
+
9
+ PASS=true
10
+
11
+ echo "\nValidating Javascript:\n"
12
+
13
+ ESLINT="$(git rev-parse --show-toplevel)/node_modules/.bin/eslint"
14
+
15
+ for FILE in $STAGED_FILES
16
+ do
17
+ "$ESLINT" "$FILE"
18
+
19
+ if [[ "$?" == 0 ]]; then
20
+ echo "\t\033[32mESLint Passed: $FILE\033[0m"
21
+ else
22
+ echo "\t\033[41mESLint Failed: $FILE\033[0m"
23
+ PASS=false
24
+ fi
25
+ done
26
+
27
+ echo "\nJavascript validation completed!\n"
28
+
29
+ if ! $PASS; then
30
+ echo "\033[41mESLINT FAILED:\033[0m Your commit contains files that should pass ESLint but do not. Please fix the ESLint errors and try again.\n"
31
+ exit 1
32
+ else
33
+ echo "\033[42mESLINT SUCCEEDED\033[0m\n"
34
+ fi
35
+
36
+ exit $?
@@ -0,0 +1,3 @@
1
+ #!/bin/sh
2
+
3
+ npm test
@@ -0,0 +1,15 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "weekly"
7
+ commit-message:
8
+ prefix: "fix"
9
+
10
+ - package-ecosystem: "npm"
11
+ directory: "/"
12
+ schedule:
13
+ interval: "daily"
14
+ commit-message:
15
+ prefix: "fix"
@@ -0,0 +1,72 @@
1
+ # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2
+ # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
3
+
4
+ name: Test & Publish
5
+
6
+ on:
7
+ push:
8
+ branches: [ "main" ]
9
+ pull_request:
10
+ branches: [ "main" ]
11
+
12
+ jobs:
13
+ test:
14
+ name: Test
15
+ runs-on: ubuntu-latest
16
+ strategy:
17
+ matrix:
18
+ node-version: [14.x, 16.x, 18.x]
19
+ steps:
20
+ - uses: actions/checkout@v3
21
+ - name: Use Node.js ${{ matrix.node-version }}
22
+ uses: actions/setup-node@v3
23
+ with:
24
+ node-version: ${{ matrix.node-version }}
25
+ cache: 'npm'
26
+ - run: npm ci
27
+ - run: npm test
28
+
29
+ analyze:
30
+ name: Analyze
31
+ runs-on: ubuntu-latest
32
+ permissions:
33
+ actions: read
34
+ contents: read
35
+ security-events: write
36
+ strategy:
37
+ fail-fast: false
38
+ steps:
39
+ - name: Checkout repository
40
+ uses: actions/checkout@v3
41
+ - name: Initialize CodeQL
42
+ uses: github/codeql-action/init@v2
43
+ with:
44
+ languages: javascript
45
+ - name: Use Node.js ${{ matrix.node-version }}
46
+ uses: actions/setup-node@v3
47
+ with:
48
+ node-version: ${{ matrix.node-version }}
49
+ cache: 'npm'
50
+ - run: npm ci
51
+ - name: Perform CodeQL Analysis
52
+ uses: github/codeql-action/analyze@v2
53
+ with:
54
+ category: "/language:javascript"
55
+
56
+ publish:
57
+ name: Publish to NPM
58
+ if: ${{ github.ref == 'refs/heads/main' }}
59
+ runs-on: ubuntu-latest
60
+ needs: [test, analyze]
61
+ steps:
62
+ - uses: actions/checkout@v3
63
+ - name: Use Node.js ${{ matrix.node-version }}
64
+ uses: actions/setup-node@v3
65
+ with:
66
+ node-version: ${{ matrix.node-version }}
67
+ cache: 'npm'
68
+ - run: npm ci
69
+ - run: npm run semantic-release
70
+ env:
71
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
72
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ <h1 align="center" style="border-bottom: none;">jest-matcher-http</h1>
2
+ <h3 align="center">Extension for <a href="https://facebook.github.io/jest">Jest</a> providing http-related matchers.</h3>
3
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/jest-matcher-http">
5
+ <img alt="npm latest version" src="https://img.shields.io/npm/v/jest-matcher-http/latest.svg">
6
+ </a>
7
+ <a href="https://github.com/rimesime/jest-matcher-http/actions?query=workflow%3ATest+branch%3Amain">
8
+ <img alt="Build states" src="https://github.com/semantic-release/semantic-release/workflows/Test/badge.svg">
9
+ </a>
10
+ <a href="#badge">
11
+ <img alt="semantic-release: angular" src="https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release">
12
+ </a>
13
+ </p>
14
+
15
+
16
+ Jest [matchers](https://jestjs.io/docs/using-matchers) (`toReturnHttpStatus`, `toReturnHttpHeader`) to [expect](https://jestjs.io/docs/expect) http responses.
17
+
18
+ Logs received body and headers if response is not as expected.
19
+
20
+
21
+ # Installation & Configuration
22
+
23
+ With npm:
24
+
25
+ ```shell
26
+ $ npm install --save-dev jest-matcher-http
27
+ ```
28
+
29
+ Either, or:
30
+ * Via configuration - Add this package to your `jest.config.js`:
31
+ ```
32
+ setupFilesAfterEnv: ['jest-matcher-http'],
33
+ ```
34
+
35
+ * Or, if you need fine-grained control, load specific matchers in your test file:
36
+ ```javascript
37
+ const { toReturnHttpCode } = require('jest-matcher-http');
38
+
39
+ expect.extend({ toReturnHttpCode });
40
+ ```
41
+
42
+ # Usage
43
+
44
+ ```javascript
45
+ expect(response).toReturnHttpStatus(307);
46
+ expect(response).toReturnHttpHeader('Location', '/v1/new-path');
47
+ ```
48
+
49
+ ## Log Output Example
50
+ ```bash
51
+ expected http status code 500 to equal 307
52
+
53
+ server responded with body:
54
+ {
55
+ "requestId": "<uuid>",
56
+ "message": "Some helpful information."
57
+ }
58
+
59
+ server responded with headers:
60
+ {
61
+ "content-type": "application/json",
62
+ ...
63
+ }
64
+ ```
65
+
66
+ ## Extended Example
67
+ ```javascript
68
+ const supertest = require('supertest');
69
+ const request = supertest('www.the-host.com');
70
+
71
+ describe('Example', () => {
72
+ it('should accept empty object', async () => {
73
+ const response = await request
74
+ .post('/v1/objects')
75
+ .send({});
76
+
77
+ expect(response).toReturnHttpCode(200);
78
+ })
79
+
80
+ it('should redirect', async () => {
81
+ const response = await request
82
+ .get('/v1/old-path');
83
+
84
+ expect(response).toReturnHttpStatus(307);
85
+ expect(response).toReturnHttpHeader('Location', '/v1/new-path');
86
+ })
87
+ });
88
+ ```
89
+
90
+ # Contributing
91
+
92
+ 1. Clone the repository:
93
+ ```shell
94
+ $ git clone git@github.com:rimesime/jest-matcher-http.git
95
+ ```
96
+
97
+ 1. This repository uses conventional commits that are validated using `git-conventional-commits`. To validate this automatically, git-hooks need to be enabled manually after cloning this repository:
98
+ ```shell
99
+ $ git config core.hooksPath .git-hooks
100
+ ```
101
+
102
+ 1. Install dependencies:
103
+ ```shell
104
+ $ npm ci
105
+ ```
106
+
107
+ 1. Test:
108
+ ```shell
109
+ $ npm test
110
+ ```
111
+
112
+ 1. Commit (using commitizen for semantic releases):
113
+ ```shell
114
+ $ npm run commit
115
+ ```
116
+
117
+ # License
118
+
119
+ This is free software, distributed under the [ISC license](https://opensource.org/licenses/ISC).
@@ -0,0 +1,213 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * For a detailed explanation regarding each configuration property, visit:
5
+ * https://jestjs.io/docs/configuration
6
+ */
7
+
8
+ module.exports = {
9
+ // All imported modules in your tests should be mocked automatically
10
+ // automock: false,
11
+
12
+ // Stop running tests after `n` failures
13
+ // bail: 0,
14
+
15
+ // The directory where Jest should store its cached dependency information
16
+ // cacheDirectory: "/private/var/folders/d_/f95lcbvs6bsfqsf8pvd4zngm0000gn/T/jest_dx",
17
+
18
+ // Automatically clear mock calls, instances, contexts and results before every test
19
+ clearMocks: true,
20
+
21
+ // Indicates whether the coverage information should be collected while executing the test
22
+ collectCoverage: true,
23
+
24
+ // An array of glob patterns indicating a set of files for which coverage information
25
+ // should be collected
26
+ collectCoverageFrom: ['<rootDir>/src/**/*.js'],
27
+
28
+ // The directory where Jest should output its coverage files
29
+ coverageDirectory: 'build/coverage/unit',
30
+
31
+ // An array of regexp pattern strings used to skip coverage collection
32
+ coveragePathIgnorePatterns: ['node_modules'],
33
+
34
+ // Indicates which provider should be used to instrument code for coverage
35
+ coverageProvider: 'v8',
36
+
37
+ // A list of reporter names that Jest uses when writing coverage reports
38
+ // coverageReporters: [
39
+ // "json",
40
+ // "text",
41
+ // "lcov",
42
+ // "clover"
43
+ // ],
44
+
45
+ // An object that configures minimum threshold enforcement for coverage results
46
+ coverageThreshold: {
47
+ global: {
48
+ branches: 100,
49
+ functions: 100,
50
+ lines: 100,
51
+ statements: 100,
52
+ },
53
+ },
54
+
55
+ // A path to a custom dependency extractor
56
+ // dependencyExtractor: undefined,
57
+
58
+ // Make calling deprecated APIs throw helpful error messages
59
+ // errorOnDeprecated: false,
60
+
61
+ // The default configuration for fake timers
62
+ // fakeTimers: {
63
+ // "enableGlobally": false
64
+ // },
65
+
66
+ // Force coverage collection from ignored files using an array of glob patterns
67
+ // forceCoverageMatch: [],
68
+
69
+ // A path to a module which exports an async function that is triggered once before
70
+ // all test suites
71
+ // globalSetup: undefined,
72
+
73
+ // A path to a module which exports an async function that is triggered once after all test suites
74
+ // globalTeardown: undefined,
75
+
76
+ // A set of global variables that need to be available in all test environments
77
+ // globals: {},
78
+
79
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number.
80
+ // E.g.maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker
81
+ // number.maxWorkers: 2 will use a maximum of 2 workers.
82
+ // maxWorkers: "50%",
83
+
84
+ // An array of directory names to be searched recursively up from the requiring module's location
85
+ // moduleDirectories: [
86
+ // "node_modules"
87
+ // ],
88
+
89
+ // An array of file extensions your modules use
90
+ // moduleFileExtensions: [
91
+ // "js",
92
+ // "mjs",
93
+ // "cjs",
94
+ // "jsx",
95
+ // "ts",
96
+ // "tsx",
97
+ // "json",
98
+ // "node"
99
+ // ],
100
+
101
+ // A map from regular expressions to module names or to arrays of module names that allow to
102
+ // stub out resources with a single module
103
+ // moduleNameMapper: {},
104
+
105
+ // An array of regexp pattern strings, matched against all module paths before
106
+ // considered 'visible' to the module loader
107
+ // modulePathIgnorePatterns: [],
108
+
109
+ // Activates notifications for test results
110
+ // notify: false,
111
+
112
+ // An enum that specifies notification mode. Requires { notify: true }
113
+ // notifyMode: "failure-change",
114
+
115
+ // A preset that is used as a base for Jest's configuration
116
+ // preset: undefined,
117
+
118
+ // Run tests from one or more projects
119
+ // projects: undefined,
120
+
121
+ // Use this configuration option to add custom reporters to Jest
122
+ // reporters: undefined,
123
+
124
+ // Automatically reset mock state before every test
125
+ // resetMocks: false,
126
+
127
+ // Reset the module registry before running each individual test
128
+ // resetModules: false,
129
+
130
+ // A path to a custom resolver
131
+ // resolver: undefined,
132
+
133
+ // Automatically restore mock state and implementation before every test
134
+ // restoreMocks: false,
135
+
136
+ // The root directory that Jest should scan for tests and modules within
137
+ // rootDir: undefined,
138
+
139
+ // A list of paths to directories that Jest should use to search for files in
140
+ roots: ['<rootDir>/src'],
141
+
142
+ // Allows you to use a custom runner instead of Jest's default test runner
143
+ // runner: "jest-runner",
144
+
145
+ // The paths to modules that run some code to configure or set up the testing
146
+ // environment before each test
147
+ // setupFiles: [],
148
+
149
+ // A list of paths to modules that run some code to configure or set up the
150
+ // testing framework before each test
151
+ setupFilesAfterEnv: ['./src/index.js'],
152
+
153
+ // The number of seconds after which a test is considered as slow and reported
154
+ // as such in the results.
155
+ // slowTestThreshold: 5,
156
+
157
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
158
+ // snapshotSerializers: [],
159
+
160
+ // The test environment that will be used for testing
161
+ // testEnvironment: "jest-environment-node",
162
+
163
+ // Options that will be passed to the testEnvironment
164
+ // testEnvironmentOptions: {},
165
+
166
+ // Adds a location field to test results
167
+ // testLocationInResults: false,
168
+
169
+ // The glob patterns Jest uses to detect test files
170
+ // testMatch: [
171
+ // "**/__tests__/**/*.[jt]s?(x)",
172
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
173
+ // ],
174
+
175
+ // An array of regexp pattern strings that are matched against all test paths,
176
+ // matched tests are skipped
177
+ // testPathIgnorePatterns: [
178
+ // "/node_modules/"
179
+ // ],
180
+
181
+ // The regexp pattern or array of patterns that Jest uses to detect test files
182
+ // testRegex: [],
183
+
184
+ // This option allows the use of a custom results processor
185
+ // testResultsProcessor: undefined,
186
+
187
+ // This option allows use of a custom test runner
188
+ // testRunner: "jest-circus/runner",
189
+
190
+ // A map from regular expressions to paths to transformers
191
+ // transform: undefined,
192
+
193
+ // An array of regexp pattern strings that are matched against all source file paths,
194
+ // matched files will skip transformation
195
+ // transformIgnorePatterns: [
196
+ // "/node_modules/",
197
+ // "\\.pnp\\.[^\\/]+$"
198
+ // ],
199
+
200
+ // An array of regexp pattern strings that are matched against all modules before
201
+ // the module loader will automatically return a mock for them
202
+ // unmockedModulePathPatterns: undefined,
203
+
204
+ // Indicates whether each individual test should be reported during the run
205
+ // verbose: undefined,
206
+
207
+ // An array of regexp patterns that are matched against all source file paths
208
+ // before re-running tests in watch mode
209
+ // watchPathIgnorePatterns: [],
210
+
211
+ // Whether to use watchman for file crawling
212
+ // watchman: true,
213
+ };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "jest-matcher-http",
3
+ "version": "1.0.1",
4
+ "description": "Additional Jest matchers for HTTP responses.",
5
+ "main": "src/index.js",
6
+ "scripts": {
7
+ "test": "jest --coverage --config jest.unit.config.js",
8
+ "acp": "git add . && npm run commit && git push",
9
+ "commit": "git-cz",
10
+ "semantic-release": "semantic-release --branches main"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/rimesime/jest-matcher-http.git"
15
+ },
16
+ "author": "Simon Schmitt (mail@simonschmitt.com)",
17
+ "license": "ISC",
18
+ "bugs": {
19
+ "url": "https://github.com/rimesime/jest-matcher-http/issues"
20
+ },
21
+ "homepage": "https://github.com/rimesime/jest-matcher-http#readme",
22
+ "release": {
23
+ "branches": [
24
+ "main"
25
+ ],
26
+ "repositoryUrl": "git+ssh://git@github.com/rimesime/jest-matcher-http.git",
27
+ "plugins": [
28
+ "@semantic-release/commit-analyzer",
29
+ "@semantic-release/release-notes-generator",
30
+ "@semantic-release/npm",
31
+ "@semantic-release/github"
32
+ ]
33
+ },
34
+ "devDependencies": {
35
+ "commitizen": "^4.2.5",
36
+ "cz-conventional-changelog": "^3.3.0",
37
+ "eslint": "^8.28.0",
38
+ "eslint-config-airbnb-base": "^15.0.0",
39
+ "eslint-plugin-import": "^2.26.0",
40
+ "eslint-plugin-jest": "^27.1.6",
41
+ "eslint-plugin-jsdoc": "^39.6.4",
42
+ "jest": "^29.3.1",
43
+ "semantic-release": "^19.0.5"
44
+ },
45
+ "dependencies": {
46
+ "@jest/globals": "^29.3.1"
47
+ },
48
+ "config": {
49
+ "commitizen": {
50
+ "path": "./node_modules/cz-conventional-changelog"
51
+ }
52
+ }
53
+ }
package/src/index.js ADDED
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ const { expect } = require('@jest/globals');
4
+ const matchers = require('./matchers');
5
+
6
+ expect.extend(matchers);
7
+
8
+ module.exports = matchers;
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ const matchers = require('./index');
4
+
5
+ describe('index', () => {
6
+ it('should add matchers', () => {
7
+ expect(expect.toReturnHttpCode).toBeDefined();
8
+ expect(expect.toReturnHttpHeader).toBeDefined();
9
+ });
10
+
11
+ it('should export matchers', () => {
12
+ expect(matchers.toReturnHttpCode).toBeDefined();
13
+ expect(matchers.toReturnHttpHeader).toBeDefined();
14
+ });
15
+ });
@@ -0,0 +1,60 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Expect a http request to return given http status code.
5
+ * Log response body and headers otherwise.
6
+ *
7
+ * @param {{status: number, body: any, headers: any}} response - The response of the request.
8
+ * @param {number} expectedHttpStatusCode - The expected http status code.
9
+ * @returns {{message: Function, pass: boolean}} The expect result according to jest.
10
+ * @see {@link https://jestjs.io/docs/expect#expectextendmatchers}
11
+ */
12
+ function toReturnHttpCode(response, expectedHttpStatusCode) {
13
+ const { status, body, headers } = response;
14
+
15
+ const pass = status === expectedHttpStatusCode;
16
+
17
+ if (pass) {
18
+ return { pass };
19
+ }
20
+
21
+ return {
22
+ pass,
23
+ message: () => `expected http status code ${status} to equal ${expectedHttpStatusCode}\n\n`
24
+ + `server responded with body:\n${JSON.stringify(body, null, 2)}\n\n`
25
+ + `server responded with headers:\n${JSON.stringify(headers, null, 2)}`,
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Expect a http request to return the given http header.
31
+ * Log response body and headers otherwise.
32
+ *
33
+ * @param {{body: any, headers: any}} response - The response of the request.
34
+ * @param {string} headerField - The expected http header field.
35
+ * @param {string} headerValue - The expected http header value.
36
+ * @returns {{message: Function, pass: boolean}} The expect result according to jest.
37
+ * @see {@link https://jestjs.io/docs/expect#expectextendmatchers}
38
+ */
39
+ function toReturnHttpHeader(response, headerField, headerValue) {
40
+ const { body, headers } = response;
41
+ const headerFieldLowerCase = headerField.toLowerCase();
42
+
43
+ const pass = headers[headerFieldLowerCase] === headerValue;
44
+
45
+ if (pass) {
46
+ return { pass };
47
+ }
48
+
49
+ return {
50
+ pass,
51
+ message: () => `expected http header "${headerFieldLowerCase}" with value "${headerValue}"\n\n`
52
+ + `server responded with body:\n${JSON.stringify(body, null, 2)}\n\n`
53
+ + `server responded with headers:\n${JSON.stringify(headers, null, 2)}`,
54
+ };
55
+ }
56
+
57
+ module.exports = {
58
+ toReturnHttpCode,
59
+ toReturnHttpHeader,
60
+ };
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ describe('matchers', () => {
4
+ describe('toReturnHttpCode', () => {
5
+ it('should succeed if http code is as expected', async () => {
6
+ const response = {
7
+ status: 200,
8
+ body: {},
9
+ headers: {},
10
+ };
11
+
12
+ expect(response).toReturnHttpCode(response.status);
13
+ });
14
+
15
+ it('should fail if http code is not as expected', async () => {
16
+ const response = {
17
+ status: 200,
18
+ body: {},
19
+ headers: {},
20
+ };
21
+
22
+ let caughtError;
23
+ try {
24
+ expect(response).toReturnHttpCode(1);
25
+ } catch (error) {
26
+ caughtError = error;
27
+ }
28
+
29
+ expect(caughtError.message).toBe(
30
+ 'expected http status code 200 to equal 1\n'
31
+ + '\n'
32
+ + 'server responded with body:\n'
33
+ + '{}\n'
34
+ + '\n'
35
+ + 'server responded with headers:\n'
36
+ + '{}',
37
+ );
38
+ });
39
+ });
40
+
41
+ describe('toReturnHttpHeader', () => {
42
+ it('should succeed if http header is as expected', async () => {
43
+ const response = {
44
+ status: 200,
45
+ body: {},
46
+ headers: {
47
+ 'request-id': 'some-uuid',
48
+ },
49
+ };
50
+
51
+ expect(response).toReturnHttpHeader('request-id', 'some-uuid');
52
+ });
53
+
54
+ it('should fail if http header is not as expected', async () => {
55
+ const response = {
56
+ status: 200,
57
+ body: {},
58
+ headers: {},
59
+ };
60
+
61
+ let caughtError;
62
+ try {
63
+ expect(response).toReturnHttpHeader('request-id', 'some-uuid');
64
+ } catch (error) {
65
+ caughtError = error;
66
+ }
67
+
68
+ expect(caughtError.message).toBe(
69
+ 'expected http header "request-id" with value "some-uuid"\n'
70
+ + '\n'
71
+ + 'server responded with body:\n'
72
+ + '{}\n'
73
+ + '\n'
74
+ + 'server responded with headers:\n'
75
+ + '{}',
76
+ );
77
+ });
78
+ });
79
+ });