我如何才能在开玩笑的情况下测试服务电话

时间:2019-04-24 10:54:29

标签: javascript unit-testing testing jestjs

我正在尝试开玩笑地测试服务电话

这是我的代码:

service.js

uploadSomething = filename => {
   return Api.post('/test')
     .then(response => {return response.data;})
     .catch(error => { return Promise.reject(error); }); 
};

myComponent.js

componentDidMount() {
    this.service = new Service();
  }

onUploadFile = event => {
    const resp = this.service.uploadSomething(event.target.href);
    resp.then(response => {
      console.log(response.data); 
    });
}

和我的测试:

const event = {
  target: {
      href: 'test',
  }
}
const wrapper = shallow(<myComponent />);
const myComponentInstance = wrapper.instance();
myComponentInstance.onUploadFile(event);

我尝试将.then添加到myComponentInstance.onUploadFile(event),但失败,它将返回

  

无法读取未定义的属性'then',有人可以告诉我如何进行测试

1 个答案:

答案 0 :(得分:1)

这是解决方案:

myComponent.tsx

import React, { Component } from 'react';
import { Service } from './service';

class MyComponent extends Component {
  private service;

  public componentDidMount() {
    this.service = new Service();
  }

  public onUploadFile = event => {
    const resp = this.service.uploadSomething(event.target.href);
    return resp.then(response => {
      console.log(response.data);
    });
  }

  public render() {
    return <div>my component</div>;
  }
}

export default MyComponent;

service.ts

const Api = {
  async post(url) {
    return { data: { data: 'real data' } };
  }
};

export class Service {
  public uploadSomething = filename => {
    return Api.post('/test')
      .then(response => {
        return response.data;
      })
      .catch(error => {
        return Promise.reject(error);
      });
  }
}

myComponent.spec.tsx

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './myComponent';
import { Service } from './service';

jest.mock('./service.ts', () => {
  const mockedService = {
    uploadSomething: jest.fn()
  };
  return {
    Service: jest.fn(() => mockedService)
  };
});

const service = new Service();

describe('MyComponent', () => {
  afterEach(() => {
    jest.resetAllMocks();
    jest.restoreAllMocks();
  });
  it('should upload file correctly', async () => {
    const event = {
      target: {
        href: 'test'
      }
    };
    const mockedResponse = { data: 'mocked response' };
    (service.uploadSomething as jest.MockedFunction<typeof service.uploadSomething>).mockResolvedValueOnce(
      mockedResponse
    );
    const logSpy = jest.spyOn(console, 'log');
    const wrapper = shallow(<MyComponent></MyComponent>);
    const myComponentInstance = wrapper.instance() as any;
    const actualValue = await myComponentInstance.onUploadFile(event);
    expect(actualValue).toBeUndefined();
    expect(logSpy).toBeCalledWith(mockedResponse.data);
  });
});

具有100%覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/55828418/myComponent.spec.tsx
  MyComponent
    ✓ should upload file correctly (24ms)

  console.log node_modules/jest-mock/build/index.js:860
    mocked response

-----------------|----------|----------|----------|----------|-------------------|
File             |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files        |      100 |      100 |      100 |      100 |                   |
 myComponent.tsx |      100 |      100 |      100 |      100 |                   |
-----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.79s, estimated 7s

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55828418