Skip to content

Commit 8126231

Browse files
committed
fix unit tetss
1 parent 4989a45 commit 8126231

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

packages/ast-tools/src/change.spec.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,17 @@ describe('Change', () => {
9696
let sourceFile = path.join(sourcePath, 'remove-replace-file.txt');
9797
expect(() => new ReplaceChange(sourceFile, -6, 'hello', ' world!')).toThrow();
9898
});
99+
it('fails for invalid replacement', () => {
100+
let sourceFile = path.join(sourcePath, 'replace-file.txt');
101+
let changeInstance = new ReplaceChange(sourceFile, 0, 'foobar', '');
102+
return changeInstance
103+
.apply(NodeHost)
104+
.then(() => expect(false).toBe(true), err => {
105+
// Check that the message contains the string to replace and the string from the file.
106+
expect(err.message).toContain('foobar');
107+
expect(err.message).toContain('import');
108+
});
109+
});
99110
it('adds string to the position of an empty string', () => {
100111
let sourceFile = path.join(sourcePath, 'replace-file.txt');
101112
let changeInstance = new ReplaceChange(sourceFile, 9, '', 'BarComponent, ');
@@ -108,7 +119,7 @@ describe('Change', () => {
108119
});
109120
it('removes the given string only if an empty string to add is given', () => {
110121
let sourceFile = path.join(sourcePath, 'remove-replace-file.txt');
111-
let changeInstance = new ReplaceChange(sourceFile, 9, ' as foo', '');
122+
let changeInstance = new ReplaceChange(sourceFile, 8, ' as foo', '');
112123
return changeInstance
113124
.apply(NodeHost)
114125
.then(() => readFile(sourceFile, 'utf8'))

packages/ast-tools/src/change.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,11 +156,10 @@ export class ReplaceChange implements Change {
156156
return host.read(this.path).then(content => {
157157
const prefix = content.substring(0, this.pos);
158158
const suffix = content.substring(this.pos + this.oldText.length);
159-
const replacedText = content.substring(this.pos,
160-
this.pos + this.oldText.length) !== this.oldText;
159+
const text = content.substring(this.pos, this.pos + this.oldText.length);
161160

162-
if (replacedText) {
163-
throw new Error(`Invalid replace: "${replacedText}" != "${this.oldText}".`);
161+
if (text !== this.oldText) {
162+
return Promise.reject(new Error(`Invalid replace: "${text}" != "${this.oldText}".`));
164163
}
165164
// TODO: throw error if oldText doesn't match removed string.
166165
return host.write(this.path, `${prefix}${this.newText}${suffix}`);

0 commit comments

Comments
 (0)