Skip to content

Commit 83a78d9

Browse files
committed
improve test setup
1 parent aa101c8 commit 83a78d9

File tree

1 file changed

+40
-29
lines changed

1 file changed

+40
-29
lines changed

typescript/src/application.test.ts

Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -5,47 +5,60 @@ import { TaskList } from '../src/task_list';
55
class TestContext {
66
input = new PassThrough();
77
output = new PassThrough();
8-
expectations: (() => boolean)[] = [];
9-
tl = new TaskList(this.input, this.output);
10-
11-
async run() {
12-
this.tl.run();
8+
taskList = new TaskList(this.input, this.output);
9+
run() {
10+
this.taskList.run();
11+
}
1312

14-
for (const expectation of this.expectations) {
15-
await new Promise<void>((resolve) =>
16-
this.output.once('readable', () => {
17-
if (expectation()) resolve();
18-
}),
19-
);
13+
emptyOutput() {
14+
while (this.output.read()) {
15+
// Clear the output stream
2016
}
17+
}
2118

22-
this.input.end();
23-
this.output.end();
19+
sendCommand(command: string) {
20+
this.emptyOutput();
21+
this.input.write(`${command}\n`);
2422
}
2523

26-
expectOutput(lines: string[]) {
27-
let text = lines.join('\n') + '\n';
28-
this.expectations.push(() => {
29-
const data = this.output.read(text.length)?.toString();
30-
expect(data).toBe(text);
31-
return !!data;
32-
});
24+
getOutput() {
25+
let output = '';
26+
let chunk = this.output.read();
27+
if (chunk === null) {
28+
return null;
29+
}
30+
while (chunk !== null) {
31+
output += chunk.toString();
32+
chunk = this.output.read();
33+
}
34+
return output;
35+
}
36+
getOutputWithoutPrompt() {
37+
const output = this.getOutput();
38+
if (output === null) {
39+
return null;
40+
}
41+
// expect ends with '> ' and remove it
42+
expect(output.endsWith('\n> ')).toBe(true);
43+
return output.slice(0, -3); // Remove the trailing '> '
3344
}
3445

35-
sendCommand(command: string) {
36-
this.expectations.push(() => {
37-
const prompt = this.output.read(2)?.toString();
38-
expect(prompt).toBe('> ');
39-
this.input.write(`${command}\n`);
40-
return !!prompt;
41-
});
46+
expectOutput(lines: string[]) {
47+
const output = this.getOutputWithoutPrompt();
48+
if (output === null) {
49+
throw new Error('Output is null');
50+
}
51+
const expectedOutput = lines.join('\n');
52+
expect(output).toBe(expectedOutput);
4253
}
4354
}
4455

4556
describe('TaskList Application', () => {
4657
test('full interaction test', async () => {
4758
const ctx = new TestContext();
4859

60+
ctx.run();
61+
4962
ctx.sendCommand('show');
5063

5164
ctx.sendCommand('add project secrets');
@@ -84,7 +97,5 @@ describe('TaskList Application', () => {
8497
'',
8598
]);
8699
ctx.sendCommand('quit');
87-
88-
await ctx.run();
89100
});
90101
});

0 commit comments

Comments
 (0)