测试异步-Promise Jest

时间:2019-06-19 19:14:25

标签: javascript unit-testing jestjs

尝试运行以下功能的测试:使用JEST和酶来反应JS

async patchAccount() {
const { user, services, FirmId } = this.props; 
let StatusChanged = this.state.AccountStatus && (this.state.AccountStatus.value !== this.state.StartingStatus)
  let AccountBody = { 
    AccountName: this.state.AccountName,
    AccountTitle: this.state.AccountTitle,
  }
  if(StatusChanged) {
    AccountBody.AccountStatusDate = new Date().toISOString().slice(0, 19).concat('Z');
  }
  let response = await Models.patchAccount({ 
    user,
    services,
    body: AccountBody,
    firmId: FirmId,
    id: this.props.accountToEdit
    })
  if(!response.error) {
    return true;
  } else {
    return false;
  }  

这是我设置测试文件account.test.js的方式

it('Test patchAccount function ',async() => {
  Models.postAccounts = jest.fn().mockImplementation(() => Promise.resolve(
   {error: false},
   {error: true},
   ))
  wrapper.setProps({
   user:{},
   services:[],
   FirmId:[],
   accountToEdit:[]
 })
 wrapper.find('AccountForm').setState({
   AccountBody:{},
   AccountStatus:""
 });
 wrapper.update();
 await expect(wrapper.find('AccountForm').instance().patchAccount()).toBeDefined()
});

我该如何正确测试它并确保兑现承诺。还尝试使用“ HaveBeenCalled()”调用模拟函数,但无法正常工作。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是解决方案,不知道您的组件JSX结构,因此我只是简单地突出显示最重要的部分。

index.tsx

import React from 'react';
import * as Models from './Models';

export interface IPornComponentProps {
  accountToEdit: string;
  user: object;
  services: any[];
  FirmId: string;
}

interface IPornComponentState {
  AccountName: string;
  AccountTitle: string;
  AccountStatus: {
    value: string;
  };
  StartingStatus: string;
}

export class PornComponent extends React.Component<IPornComponentProps, IPornComponentState> {
  constructor(props: IPornComponentProps) {
    super(props);
    this.state = {
      AccountName: '',
      AccountTitle: '',
      AccountStatus: {
        value: ''
      },
      StartingStatus: ''
    };
  }

  public async patchAccount() {
    const { user, services, FirmId } = this.props;
    const StatusChanged = this.state.AccountStatus && this.state.AccountStatus.value !== this.state.StartingStatus;
    const AccountBody = {
      AccountName: this.state.AccountName,
      AccountTitle: this.state.AccountTitle,
      AccountStatusDate: '2019-01-01'
    };
    if (StatusChanged) {
      AccountBody.AccountStatusDate = new Date()
        .toISOString()
        .slice(0, 19)
        .concat('Z');
    }
    const response = await Models.patchAccount({
      user,
      services,
      body: AccountBody,
      firmId: FirmId,
      id: this.props.accountToEdit
    });
    if (!response.error) {
      return true;
    } else {
      return false;
    }
  }

  public render() {
    return <div>Unit Test</div>;
  }
}

Models.ts

import console = require('console');

export async function patchAccount(...args) {
  return { error: true };
}

index.spec.tsx

import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import { PornComponent, IPornComponentProps } from './';
import * as Models from './Models';

describe('PornComponent', () => {
  let wrapper: ShallowWrapper;
  const mockedProps: IPornComponentProps = {
    accountToEdit: '1',
    user: {},
    services: [],
    FirmId: '2'
  };
  beforeEach(() => {
    wrapper = shallow(<PornComponent {...mockedProps}></PornComponent>);
  });

  it('Test patchAccount function', async () => {
    const patchAccountSpy = jest.spyOn(Models, 'patchAccount').mockResolvedValueOnce({ error: false });
    const actualValue = await (wrapper.instance() as any).patchAccount();
    expect(actualValue).toBeTruthy();
    expect(patchAccountSpy).toBeCalledWith({
      user: {},
      services: [],
      body: { AccountName: '', AccountTitle: '', AccountStatusDate: '2019-01-01' },
      firmId: '2',
      id: '1'
    });
    patchAccountSpy.mockRestore();
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/56674440/index.spec.tsx (5.588s)
  PornComponent
    ✓ Test patchAccount function (18ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    83.33 |       75 |       80 |       85 |                   |
 Models.ts |    33.33 |      100 |        0 |       50 |                 4 |
 index.tsx |    90.48 |       75 |      100 |    88.89 |             42,57 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        6.479s

其他代码分支可以用相同的方式进行测试。

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