简体   繁体   English

测试异步 - Promise Jest

[英]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 :这是我如何设置我的测试文件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.还尝试使用HaveBeenCalled()调用模拟函数但没有奏效。 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.这里是解决方案,不知道你的组件JSX结构,所以我简单地突出显示最重要的部分。

index.tsx : 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 : Models.ts

import console = require('console');

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

index.spec.tsx : 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这是完整的演示: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56674440

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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