or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

assertions.mdhttp-client.mdhttp-utilities.mdindex.mdrequest-response-mocking.mdtest-doubles.mdtest-sandbox.mdvalidation-helpers.md

index.mddocs/

0

# LoopBack TestLab

1

2

LoopBack TestLab is a comprehensive collection of testing utilities specifically designed for LoopBack 4 applications and TypeScript testing in general. It provides behavior-driven development (BDD) style assertions, complete Sinon.js integration, HTTP request/response stubs, supertest helpers, OpenAPI validation, test sandbox utilities, and various helper functions for robust test suite development.

3

4

## Package Information

5

6

- **Package Name**: @loopback/testlab

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @loopback/testlab`

10

11

## Core Imports

12

13

```typescript

14

import { expect, sinon, createClientForHandler, TestSandbox } from "@loopback/testlab";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { expect, sinon, createClientForHandler, TestSandbox } = require("@loopback/testlab");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import { expect, sinon, TestSandbox, createClientForHandler } from "@loopback/testlab";

27

28

// BDD-style assertions

29

expect(5).to.be.greaterThan(3);

30

expect([1, 2, 3]).to.have.lengthOf(3);

31

expect({name: "Alice"}).to.have.property("name", "Alice");

32

33

// Sinon integration for test doubles

34

const stub = sinon.stub();

35

stub.returns("mock result");

36

expect(stub()).to.equal("mock result");

37

38

// Test sandbox for file operations

39

const sandbox = new TestSandbox("/tmp/tests");

40

await sandbox.writeTextFile("config.json", JSON.stringify({test: true}));

41

await sandbox.reset();

42

43

// HTTP client testing

44

const client = createClientForHandler((req, res) => {

45

res.writeHead(200, {"Content-Type": "application/json"});

46

res.end(JSON.stringify({message: "Hello"}));

47

});

48

await client.get("/").expect(200).expect({message: "Hello"});

49

```

50

51

## Architecture

52

53

LoopBack TestLab is organized into distinct functional modules:

54

55

- **Assertion System**: Should.js-based BDD assertions with enhanced TypeScript support

56

- **Test Doubles**: Complete Sinon.js integration with improved stubbing utilities

57

- **HTTP Testing**: SuperTest integration and Shot-based request/response mocking for testing without servers

58

- **File System Testing**: TestSandbox for isolated file operations and test data management

59

- **Validation Utilities**: OpenAPI/Swagger specification validation and JSON conversion helpers

60

- **Test Flow Control**: Conditional test skipping and error logging utilities

61

- **Server Configuration**: HTTP/HTTPS server configuration helpers for test environments

62

63

## Capabilities

64

65

### BDD Assertions

66

67

Behavior-driven development style assertions using Should.js configured in as-function mode with enhanced TypeScript support and chai-like syntax.

68

69

```typescript { .api }

70

const expect: Internal;

71

72

interface Internal extends ShouldInternal {

73

(obj: any): ShouldAssertion;

74

use(fn: (should: Internal, Assertion: Assertion) => void): Internal;

75

}

76

```

77

78

[BDD Assertions](./assertions.md)

79

80

### Test Doubles and Mocking

81

82

Complete Sinon.js integration for spies, stubs, and mocks with enhanced TypeScript experience and improved stubbing utilities.

83

84

```typescript { .api }

85

const sinon: sinon.SinonStatic;

86

type SinonSpy = sinon.SinonSpy;

87

88

function createStubInstance<TType extends object>(

89

constructor: sinon.StubbableType<TType>

90

): StubbedInstanceWithSinonAccessor<TType>;

91

92

type StubbedInstanceWithSinonAccessor<T> = T & {

93

stubs: sinon.SinonStubbedInstance<T>;

94

};

95

```

96

97

[Test Doubles](./test-doubles.md)

98

99

### HTTP Client Testing

100

101

SuperTest integration and utilities for creating HTTP clients for testing REST applications and request handlers.

102

103

```typescript { .api }

104

const supertest: typeof import("supertest");

105

type Client = supertest.SuperTest<supertest.Test>;

106

107

function createClientForHandler(

108

handler: (req: http.IncomingMessage, res: http.ServerResponse) => void

109

): Client;

110

111

function createRestAppClient(app: RestApplicationLike): Client;

112

```

113

114

[HTTP Client Testing](./http-client.md)

115

116

### Request/Response Mocking

117

118

Shot-based HTTP request/response stubs for testing without running servers, including Express-specific context stubbing.

119

120

```typescript { .api }

121

function inject(

122

dispatchFunc: ShotListener,

123

options: ShotRequestOptions

124

): Promise<ResponseObject>;

125

126

function stubServerRequest(options: ShotRequestOptions): IncomingMessage;

127

function stubServerResponse(request: IncomingMessage, onEnd: ShotCallback): ServerResponse;

128

function stubHandlerContext(requestOptions?: ShotRequestOptions): HandlerContextStub;

129

function stubExpressContext(requestOptions?: ShotRequestOptions): ExpressContextStub;

130

```

131

132

[Request/Response Mocking](./request-response-mocking.md)

133

134

### Test Sandbox

135

136

File system utilities for creating isolated test directories and managing test data with automatic cleanup capabilities.

137

138

```typescript { .api }

139

class TestSandbox {

140

constructor(rootPath: string, options?: TestSandboxOptions);

141

get path(): string;

142

reset(): Promise<void>;

143

delete(): Promise<void>;

144

mkdir(dir: string): Promise<void>;

145

copyFile(src: string, dest?: string, transform?: (content: string) => string): Promise<void>;

146

writeJsonFile(dest: string, data: unknown): Promise<void>;

147

writeTextFile(dest: string, data: string): Promise<void>;

148

}

149

```

150

151

[Test Sandbox](./test-sandbox.md)

152

153

### HTTP Utilities

154

155

Async HTTP/HTTPS request utilities and server configuration helpers for test environments.

156

157

```typescript { .api }

158

function httpGetAsync(urlString: string, agent?: http.Agent): Promise<IncomingMessage>;

159

function httpsGetAsync(urlString: string, agent?: https.Agent): Promise<IncomingMessage>;

160

161

function givenHttpServerConfig<T extends HttpOptions | HttpsOptions>(

162

customConfig?: T

163

): HostPort & T;

164

```

165

166

[HTTP Utilities](./http-utilities.md)

167

168

### Validation and Helpers

169

170

OpenAPI/Swagger specification validation, JSON conversion utilities, test skipping helpers, and HTTP error logging.

171

172

```typescript { .api }

173

function validateApiSpec(spec: any): Promise<void>;

174

function toJSON<T>(value: T): T;

175

176

function skipIf<ARGS extends unknown[], RETVAL>(

177

skip: boolean,

178

verb: TestDefinition<ARGS, RETVAL> & {skip: TestDefinition<ARGS, RETVAL>},

179

name: string,

180

...args: ARGS

181

): RETVAL;

182

183

function skipOnTravis<ARGS extends unknown[], RETVAL>(

184

verb: TestDefinition<ARGS, RETVAL> & {skip: TestDefinition<ARGS, RETVAL>},

185

name: string,

186

...args: ARGS

187

): RETVAL;

188

```

189

190

[Validation and Helpers](./validation-helpers.md)

191

192

## Common Types

193

194

```typescript { .api }

195

interface TestSandboxOptions {

196

subdir: boolean | string;

197

}

198

199

interface RestApplicationLike {

200

restServer: RestServerLike;

201

}

202

203

interface RestServerLike {

204

url?: string;

205

rootUrl?: string;

206

}

207

208

interface HttpOptions extends ListenOptions {

209

protocol?: 'http';

210

}

211

212

interface HttpsOptions extends ListenOptions, HttpsServerOptions {

213

protocol: 'https';

214

}

215

216

interface HostPort {

217

host: string;

218

port: number;

219

}

220

221

type TestDefinition<ARGS extends unknown[], RETVAL> = (

222

name: string,

223

...args: ARGS

224

) => RETVAL;

225

```