Merge pull request #19298 from joscha/joscha/xhr-mock

add: xhr-mock
This commit is contained in:
Mine Starks
2017-09-05 16:19:24 -07:00
committed by GitHub
4 changed files with 107 additions and 0 deletions

56
types/xhr-mock/index.d.ts vendored Normal file
View File

@@ -0,0 +1,56 @@
// Type definitions for xhr-mock 1.9
// Project: https://github.com/jameslnewell/xhr-mock#readme
// Definitions by: Joscha Feth <https://github.com/joscha>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace mock {
interface Headers {
[k: string]: string;
}
interface MockResponse {
status(code: number): this;
status(): number;
statusText(statusText: string): this;
statusText(): string;
header(name: string, value: string): this;
header(name: string): string | null;
headers(obj: Headers): this;
headers(): Headers;
body(body: string): this;
body(): string;
timeout(timeout: boolean | number): this;
timeout(): boolean | number;
}
interface MockRequest {
method(): string;
url(): string;
query(): string;
header(name: string, value: string): this;
header(name: string): string | null;
headers(obj: Headers): this;
headers(): Headers;
body(body: string): this;
body(): string;
progress(loaded: number, total: number, lengthComputable?: boolean): void;
}
type MockFunction = (req: MockRequest, res: MockResponse) => MockResponse | null;
interface XhrMock {
XMLHttpRequest: XMLHttpRequest;
setup(): this;
teardown(): this;
reset(): this;
mock(method: string, url: string, fn: MockFunction): this;
get(url: string, fn: MockFunction): this;
post(url: string, fn: MockFunction): this;
put(url: string, fn: MockFunction): this;
patch(url: string, fn: MockFunction): this;
delete(url: string, fn: MockFunction): this;
}
}
declare var mock: mock.XhrMock;
export = mock;

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"xhr-mock-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,27 @@
import mock = require('xhr-mock');
// replace the real XHR object with the mock XHR object
mock.setup();
// create a mock response for all POST requests with the URL http://localhost/api/user
mock.post('http://localhost/api/user', (req: mock.MockRequest, res: mock.MockResponse) => {
// return null; //simulate an error
// return res.timeout(true); //simulate a timeout
return res
.status(201)
.header('Content-Type', 'application/json')
.body(JSON.stringify({data: {
first_name: 'John', last_name: 'Smith'
}}));
});
// create an instance of the (mock) XHR object and use as per normal
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
// when you're finished put the real XHR object back
mock.teardown();
}
};