原因
起初在开发代码中直接写localStorage.getItem(XXX), setItem(XXX)
结果在做单元测试的时候,会提示找不到windows.localStorage
为了通过测试, 我修改了
开发代码:
定义接口然后去用一个类实现接口
export interface ICache {
setItem(key: string, value: any): void;
getItem(key: string): any;
}
export class GalleryCache implements ICache {
public setItem(key: string, value: any) {
localStorage.setItem(key, value);
}
public getItem(key: string) {
return localStorage.getItem(key);
}
}
在实际组件中直接new 这个类
测试部分
有两种方法
第一种
下载一个有关依赖https://www.npmjs.com/package/mock-local-storage
npm i mock-local-storage --save-dev
,然后编写你的测试文件,(测试我用的是mocha+enzyme+chai)
先引入依赖
import "mock-local-storage";
// test cache API
describe("test cache API", () => {
// 每次都要把清除缓存,避免对下一测试造成影响
beforeEach(() => {
localStorage.clear();
// remove callback
localStorage.itemInsertionCallback = null;
});
it("cache hasn't 'interval/autoRefresh' value, save state of 'interval/autoRefresh' into cache", () => {
const cache = new Cache();
//gallery是你的组件
const gallery = enzyme.shallow(
<Gallery
loggerFactory={loggers}
translator={translators.object}
imageProvider={imageInfoProviderMocks.object}
cache={cache}
filterProvider={filterProviderMocks.object}
generatorUrl={imagePathProviderMocks.object}
/>,
);
//这里就可以直接用localStorage.getItem, setItem同理
expect(cache.getItem(intervalKey)).equal(`${gallery.state("interval")}`);
expect(cache.getItem(autoRefreshKey)).equal(
`${gallery.state("autoRefresh")}`,
"",
);
});
});
第二种
也可以用typemoq
具体用法请点击官网typemoq
//引入typemoq
import * as TypeMoq from "typemoq";
// mock cache
const cacheMock = TypeMoq.Mock.ofType<ICache>();
cacheMock
.setup(f => f.setItem(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => null);
cacheMock.setup(f => f.getItem(TypeMoq.It.isAny())).returns(() => null);
//在组件中使用
const frame = shallow(
<Gallery
…
cache={cacheMock.object}
…
/>
);