0

我正在学习用笑话和酶进行测试。我想用 moxios 测试一个 API,但面临很多挑战。我有一个 API 调用如下:

useEffect(() => {axios.get(`https://API/call/with/dynamicvalue/${id}`,
        {
            headers: {
              Authorization: `Basic ${btoa(getToken())}`,
           },
          }).then((response)=>{
              let MoreData=response.data;
              console.log(MoreData)

        setFullAuditDetails(MoreData.data.slice(0,20).map(d=>{
            return{
            timeF: d.time.split('T')[0],
            actionF: d.method,
            userF: d.userName.split('.')[0]
            }
        }))
    })}, [])

我想用 moxios 测试一下。我已经这样做了:

const api = `https://API/call/with/dynamicvalue/372c7861-e09a-41ae-8c6d-7bbc7877ad79`

describe("Tests for API", () => {
beforeEach(() => {
    moxios.install()
})

  afterEach(() => {
    moxios.uninstall()
  })

  test("Check for the response", (done) => {
    moxios.wait(() => {
        const request = moxios.stubRequest(api)
        request.respondWith({ status: 200,         
            response: {  "success": true }
    }) //mocked response
    .then(response => {
        console.log(response);
        expect('status').toEqual('200');
        done();
        wrapper2.unmount();
    })
})
        });
    })

得到错误:

TypeError: Cannot read property 'respondWith' of undefined  

  37 |         moxios.wait(() => {
  38 |             const request = moxios.stubRequest(api)  
> 39 |             request.respondWith({ status: 200,       
  
     |                     ^
  40 |                 response: {  "success": true }       
  41 |         }) //mocked response
  42 |         .then(response => {

但不知道该怎么做。任何帮助表示赞赏。

4

1 回答 1

0

终于找到了解决办法:

describe("Tests for API", () => {
    beforeEach(() => {
        moxios.install()
    })

      afterEach(() => {
        moxios.uninstall()
      })

      test("Check for the response", (done) => {
        // moxios.wait(() => {
            moxios.stubRequest(api, { status: 200,         
                response: {  "success": true }
        }) //mocked response

        axios.get(api, {  "success": true }).then(response => {
            // console.log(response);
            expect(response.status).toBe(200);
            done();
        });
    });
});
于 2020-12-14T11:38:37.730 回答