如何嘲笑节点库

时间:2020-04-07 15:08:10

标签: node.js reactjs testing mocking jestjs

由于使用一个翻译库调用'react-simple-i18n'

,我无法使用我的React组件之一

在我的React组件中,我需要从该库中导入一个函数以按如下方式使用它:

import { useI18n } from 'react-simple-i18n/lib/'

const MyComponent = ({ data }) => {
  const { t } = useI18n()

  return( 
    <div>{t('MyComponent.hello') }</div>
  )
}

如果我尝试使用Jest(简单快照)进行测试

import React from 'react'
import { shallow } from 'enzyme'
import MyComponent from './MyComponent'
import { useI18n } from 'react-simple-i18n'

const fakeData = { ... }

jest.mock('react-simple-i18n', () => {
  useI18n: () => { t: 'test' }
})

let wrapper = shallow(<MyComponent data={fakeData}/>)

describe('MyComponent', () => {
  it('should render MyComponent correctly', () => {
    expect(wrapper).toMatchSnapshot();
  })
})

我从Jest那里失败了:

TypeError:无法解构'undefined'或'null'的属性t

我该如何模拟我的useI18n函数?

1 个答案:

答案 0 :(得分:1)

您可以使用jest.mock(moduleName, factory, options)模拟库。

例如

index.jsx

import { useI18n } from 'react-simple-i18n';
import React from 'react';

const MyComponent = ({ data }) => {
  const { t } = useI18n();
  return <div>{t('MyComponent.hello')}</div>;
};

export default MyComponent;

index.test.jsx

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './';
import { useI18n } from 'react-simple-i18n';

jest.mock(
  'react-simple-i18n',
  () => {
    const mUseI18n = { t: jest.fn().mockReturnValue('test') };
    return {
      useI18n: jest.fn(() => mUseI18n),
    };
  },
  { virtual: true },
);

describe('MyComponent', () => {
  it('should render MyComponent correctly', () => {
    const fakeData = {};
    let wrapper = shallow(<MyComponent data={fakeData} />);
    expect(wrapper.text()).toBe('test');
    expect(useI18n).toBeCalledTimes(1);
    expect(useI18n().t).toBeCalledWith('MyComponent.hello');
  });
});

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

 PASS  stackoverflow/61083245/index.test.jsx (8.334s)
  MyComponent
    ✓ should render MyComponent correctly (8ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.jsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.417s

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61083245