我的 Ionic 应用程序中有一个凭证令牌存储,要执行注销操作,我需要删除存储在其中的令牌。这是我的登录服务:
// imports skipped;
export class LoginService implements CanActivate {
private authToken: string;
private httpService: string;
constructor(
private handler: HttpBackend,
private router: Router,
private storage: Storage
) {
this.httpService = new HttpClient(handler);
}
private generateToken(login: string, password: string) {
return btoa(`${login}:${password}`);
}
authenticate(login: string, password: string, webserviceURL: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: `Basic ${this.generateToken(login, password)}`
})
};
return this.httpClient.get(`http://${webserviceURL}/api/version/`, httpOptions);
}
async saveToken(login: string, password: string) {
this.authToken = this.generateToken(login, password);
return await this.storage.set('AUTH_TOKEN', this.authToken);
}
async getToken() {
return await this.storage.get('AUTH_TOKEN');
}
async clearData() {
this.authToken = null;
return await this.storage.remove('AUTH_TOKEN');
}
canActivate() {
if (this.authToken) {
return true;
}
this.router.navigateByUrl('login');
}
}
在我对这项服务的测试中,我得到了以下信息:
const expectedToken = btoa('testLogin:testPassword');
service.saveToken('testLogin', 'testPassword').then(() => {
service.getToken().then(savedToken => {
expect(savedToken).toEqual(expectedToken);
});
});
service.clearData().then(() => {
service.getToken().then(savedToken => {
expect(savedToken).toBe(null);
});
});
因此,每当我运行测试时,最后一个测试用例都会失败,因为由于某种原因,令牌没有从存储中删除。这是测试输出:Error: Expected 'dGVzdExvZ2luOnRlc3RQYXNzd29yZA==' to be null
. 我应该如何正确处理从存储中删除值?