Node.js 如何在jest中模拟节点库
由于使用了一个翻译库调用,我被React组件中的一个mock卡住了 在我的React组件中,我需要从该库导入一个函数,以便按如下方式使用它:Node.js 如何在jest中模拟节点库,node.js,reactjs,testing,mocking,jestjs,Node.js,Reactjs,Testing,Mocking,Jestjs,由于使用了一个翻译库调用,我被React组件中的一个mock卡住了 在我的React组件中,我需要从该库导入一个函数,以便按如下方式使用它: import { useI18n } from 'react-simple-i18n/lib/' const MyComponent = ({ data }) => { const { t } = useI18n() return( <div>{t('MyComponent.hello') }</div>
import { useI18n } from 'react-simple-i18n/lib/'
const MyComponent = ({ data }) => {
const { t } = useI18n()
return(
<div>{t('MyComponent.hello') }</div>
)
}
从'react-simple-i18n/lib/'导入{useI18n}
常量MyComponent=({data})=>{
常数{t}=useI18n()
报税表(
{t('MyComponent.hello')}
)
}
如果我尝试使用Jest(简单快照)进行测试
从“React”导入React
从“酶”导入{shall}
从“/MyComponent”导入MyComponent
从'react-simple-i18n'导入{useI18n}
常量fakeData={…}
jest.mock('react-simple-i18n',()=>{
useI18n:()=>{t:'test'}
})
让包装器=浅()
描述('MyComponent',()=>{
它('应该正确呈现MyComponent',()=>{
expect(wrapper.toMatchSnapshot();
})
})
我从玩笑中得到了一个失败:
TypeError:无法对“undefined”或“null”的属性t
进行分解
我如何使用useI18n函数 您可以使用来模拟库
例如
index.jsx
:
从'react-simple-i18n'导入{useI18n};
从“React”导入React;
常量MyComponent=({data})=>{
常数{t}=useI18n();
返回{t('MyComponent.hello')};
};
导出默认MyComponent;
index.test.jsx
:
从“React”导入React;
从“酶”导入{shall};
从“/”导入MyComponent;
从'react-simple-i18n'导入{useI18n};
开玩笑(
“react-simple-i18n”,
() => {
const mUseI18n={t:jest.fn().mockReturnValue('test')};
返回{
useI18n:jest.fn(()=>mUseI18n),
};
},
{virtual:true},
);
描述('MyComponent',()=>{
它('应该正确呈现MyComponent',()=>{
const fakeData={};
让包装器=浅();
expect(wrapper.text()).toBe('test');
期望(使用18N)。等待时间(1);
expect(useI18n().t).toBeCalledWith('MyComponent.hello');
});
});
100%覆盖率的单元测试结果:
PASS stackoverflow/61083245/index.test.jsx(8.334s)
真菌成分
✓ 应正确呈现MyComponent(8ms)
-----------|---------|----------|---------|---------|-------------------
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
-----------|---------|----------|---------|---------|-------------------
所有文件| 100 | 100 | 100 | 100 |
index.jsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:9.417秒
源代码:谢谢您的帮助,了解笑话模拟的工作原理对我有很大帮助@很高兴听到这个消息!
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();
})
})