我在Ionic应用程序中有一个凭证令牌存储,要执行注销操作,我需要删除其中存储的令牌。下面是我的LoginService:
// 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。我应该如何正确处理从存储中删除价值?
发布于 2019-10-08 19:32:42
第二次尝试...如果你的代码在一个方法中运行,那么它必须全部嵌套,否则它会一个接一个地运行吗?
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);
});
});
});
});发布于 2019-10-11 01:02:46
我自己还没有尝试过,但我希望下面这样的方法能起作用:
this.storage.set('AUTH_TOKEN', null);或
// Actually use a variation of this one myself for one case
this.storage.set('AUTH_TOKEN', '');编辑:如果您需要将密钥保存在本地存储中,则这两个选项都适用。Ie-您的应用程序希望密钥始终存在-无论状态如何。
https://stackoverflow.com/questions/58283411
复制相似问题