简体   繁体   中英

Test async- Promise Jest

Trying to run a test for the following function:

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;
  }  

Here is how I set up my test file 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();
});

How could I test it correctly and make sure the promise gets called. Also tried to call the mock function with the HaveBeenCalled() and did not work. I appreciate any help.

Here is the solution, don't know your component JSX structure, so I simply it to highlight the most important parts.

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();
  });
});

Unit test result with coverage report:

 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

Other code branch can be tested in the same way.

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56674440

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM