Skip to content

Commit 20e7ac1

Browse files
committed
Extend coverage and docs to cover alternative typed world
1 parent 31aa9a0 commit 20e7ac1

File tree

2 files changed

+55
-6
lines changed

2 files changed

+55
-6
lines changed

docs/state-management.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,28 @@ If you're using TypeScript, you can get optimum type safety and completion based
7373

7474
```ts
7575
interface CustomWorld extends Mocha.Context {
76-
eat: (count: number) => void;
76+
eat(count: number): void;
7777
}
7878

7979
When("I eat {int} cucumbers", function (this: CustomWorld, count: number) {
8080
this.eat(count);
8181
});
8282
```
83+
84+
Alternatively, you can extend the default type `Mocha.Context` using a declaration file like shown below.
85+
86+
```ts
87+
// declarations.d.ts
88+
interface CustomWorld {
89+
eat(count: number): void;
90+
}
91+
92+
declare namespace Mocha {
93+
interface Context extends CustomWorld {}
94+
}
95+
96+
// steps.ts
97+
When("I eat {int} cucumbers", function (count: number) {
98+
this.eat(count);
99+
});
100+
```

lib/index.test-d.ts

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,42 @@ After({ tags: "foo" }, function () {
109109
expectType<Mocha.Context>(this);
110110
});
111111

112+
expectType<messages.GherkinDocument>(window.testState.gherkinDocument);
113+
expectType<messages.Pickle[]>(window.testState.pickles);
114+
expectType<messages.Pickle>(window.testState.pickle);
115+
expectType<messages.PickleStep | undefined>(window.testState.pickleStep);
116+
117+
/**
118+
* Extending world (example #1)
119+
*/
120+
interface MathWorld {
121+
add(a: number, b: number): number;
122+
}
123+
124+
declare global {
125+
// eslint-disable-next-line @typescript-eslint/no-namespace
126+
namespace Mocha {
127+
// eslint-disable-next-line @typescript-eslint/no-empty-interface
128+
interface Context extends MathWorld {}
129+
}
130+
}
131+
132+
Given(/foo/, function () {
133+
expectType<number>(this.add(1, 2));
134+
});
135+
136+
When(/foo/, function () {
137+
expectType<number>(this.add(1, 2));
138+
});
139+
140+
Then(/foo/, function () {
141+
expectType<number>(this.add(1, 2));
142+
});
143+
144+
/**
145+
* Extending world (example #2)
146+
*/
147+
112148
interface CustomWorld extends Mocha.Context {
113149
pageDriver: {
114150
navigateTo(url: string): void;
@@ -129,8 +165,3 @@ Then(/foo/, function (this: CustomWorld, url: string) {
129165
expectType<CustomWorld>(this);
130166
this.pageDriver.navigateTo(url);
131167
});
132-
133-
expectType<messages.GherkinDocument>(window.testState.gherkinDocument);
134-
expectType<messages.Pickle[]>(window.testState.pickles);
135-
expectType<messages.Pickle>(window.testState.pickle);
136-
expectType<messages.PickleStep | undefined>(window.testState.pickleStep);

0 commit comments

Comments
 (0)