[英]Mock a provider class to return response and handle promise - Unit Testing with Jasmine and Karma with Ionic 3
[英]Unit testing ionic function which returns or uses a promise - TS2304: Cannot find name 'done' - Jasmine / Karma for unit testing ionic apps
我正在嘗試對模擬的存儲(僅在內存中使用字典)進行簡單數據訪問功能的單元測試。
當我嘗試使用done()
函數時,出現錯誤: TS2304: Cannot find name 'done'
盡管看似已正確安裝了茉莉花和業力,卻TS2304: Cannot find name 'done'
。
我所做的事情並未解決此問題:
data.ts:
export class DataProvider {
private foo;
public readonly fooKey
public getFoo() { return this.foo; }
public setFoo(bar: number) {
this.foo = bar;
this.storage.ready().then(() => {
this.storage.set(this.fooKey, JSON.stringify(this.foo));
});
}
}
data.spec.ts:
include StorageMock;
include DataProvider;
it('should have correct values after loading data',
function() {
comp.storage.set(comp.fooKey, JSON.stringify(0.1234));
comp.storage.get(comp.fooKey).then(result => {
expect(JSON.parse(result)).toEqual(0.1234);
done(); // Error - TS2304: Cannot find name 'done'
});
});
StorageMock:
export class StorageMock {
private internal = [];
public driver(): any {
return '';
}
public ready(): Promise<any> {
return new Promise(function(resolve: Function): void {
resolve({});
});
}
public get(key: string): Promise<any> {
let getval = this.internal[key];
return new Promise(function(resolve: Function): void {
resolve(getval);
});
}
public set(key: string, value: any): Promise<any> {
this.internal.push({key : value});
return new Promise(function(resolve: Function): void {
resolve();
});
}
public remove(key: string): Promise<any> {
let index = this.internal.indexOf(key);
if(index !== -1) {
this.internal.splice(index,1);
}
return new Promise(function(resolve: Function): void {
resolve();
});
}
public clear(): Promise<any> {
this.internal = [];
return new Promise(function(resolve: Function): void {
resolve();
});
}
public length(): Promise<any> {
let length = this.internal.length;
return new Promise(function(resolve: Function): void {
resolve(length);
});
}
public keys(): Promise<any> {
let keys = Object.keys(this.internal);
return new Promise(function(resolve: Function): void {
resolve(keys);
});
}
public forEach(i: any): Promise<any> {
return new Promise(function(resolve: Function): void {
resolve();
});
}
實際答案:
done
不是Jasmine框架的一部分,而是在測試的聲明中用作測試完成時的回調。 注意以下(done)
聲明:
it("should test something async", (done) => {
...do the testing...
done();
}
原始答案:
雖然我不確定為什么不能使用done()
,但似乎使用fakeAsync, flushMicrotasks, tick
的方式會使工作“完成”(存儲模擬仍然存在一些異步問題)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.