ts+react中使用window.localstorage

 

原因

起初在开发代码中直接写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}

…

      />

    );

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,似乎您想了解如何在Vue3使用TypeScript和React。Vue3和React是两个不同的框架,不能同时使用。如果您想在Vue3使用TypeScript,可以按照以下步骤进行操作: 1.安装Vue CLI并创建一个新项目: ```shell npm install -g @vue/cli vue create my-project ``` 2.在创建的Vue项目安装TypeScript: ```shell cd my-project vue add typescript ``` 3.现在您可以在Vue3项目使用TypeScript了。例如,在Vue组件使用TypeScript: ```typescript <template> <div>{{ message }}</div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ data() { return { message: 'Hello World!' } } }) </script> ``` 如果您想在Vue3使用React,可以使用Vue3的Composition API来实现。以下是一个使用Vue3和React的示例: ```typescript <template> <div> <h1>{{ title }}</h1> <ReactComponent :message="message" /> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' import { createApp } from 'vue' import React from 'react' import ReactDOM from 'react-dom' const ReactComponent = defineComponent({ props: { message: { type: String, required: true } }, mounted() { const el = document.createElement('div') document.body.appendChild(el) ReactDOM.render(<div>{this.message}</div>, el) } }) export default defineComponent({ setup() { const title = ref('Vue3 + React') const message = ref('Hello World!') return { title, message } }, components: { ReactComponent } }) </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值