我开始学习angular,尤其是在单元测试中。我有我需要为localStorage创建单元测试的情况。这是component.ts中的代码:
getRandomColor() {
if (localStorage.getItem('randomColor') === null) {
const colorCode = '7608952EAFCDBE';
this.backgroundColor = '#';
for (let i = 0; i < 6; i++) {
this.backgroundColor += colorCode[Math.floor(Math.random() * 12)];
}
localStorage.setItem('randomColor', this.backgroundColor)
return this.backgroundColor;
} else {
this.backgroundColor = localStorage.getItem('randomColor');
}
}
Inspec.ts
我是这样写的
it('getRandomColor if localStorage randomColor is null', () => {
const spyLocalStorage = spyOn(localStorage, 'getItem').andCallFake(function (key) {
spyLocalStorage = null
expect(component.backgroundColor).toEqual('#')
});
但是显示错误。这种情况下最好的方法是什么?你的帮助真替我着想。谢谢你!})
您不应该在mock函数中编写期望,这意味着返回预期值(有条件地"和callfake& quot;)或无条件地"andReturnValue"不太确定api(可以参考文档)。
-
首先,您必须模拟目标函数内部使用的所有api。
-
然后调用你想要测试的实际方法。
-
然后编写断言/期望来验证结果,如下所示。
it('getRandomColor if localStorage randomColor is null', () => {
const setItem = spyOn(localStorage, 'setItem');
spyOn(localStorage, 'getItem').andCallFake(() => null);
const result = component.getRandomColor();
expect(result).toMatch(/^#[a-fA-F0-9]{6}$/);
expect(component.backgroundColor).toEqual(result);
expect(setItem).toHaveBeenCalledWith('randomColor', result);
});