相关疑难解决方法(0)

每次测试的Jest Mock模块

我对在Jest中嘲笑如何对实现进行单元测试感到困惑.问题是我想模仿不同的预期行为.

有没有办法实现这个目标?因为导入只能在文件的顶部,并且能够模拟在导入之前必须声明的内容.我也尝试传递一个本地函数,所以我可以覆盖行为,但是jest抱怨你不允许传递任何本地函数.

jest.mock('the-package-to-mock', () => ({
  methodToMock: jest.fn(() => console.log('Hello'))
}));

import * as theThingToTest from '../../../app/actions/toTest'
import * as types from '../../../app/actions/types'

it('test1', () => {
  expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})

it('test2', () => {
  //the-package-to-mock.methodToMock should behave like something else
  expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})
Run Code Online (Sandbox Code Playgroud)

在内部你可以想象theThingToTest.someAction()使用the-package-to-mock.methodToMock

unit-testing mocking jestjs react-native

25
推荐指数
4
解决办法
2万
查看次数

在 jest.spyOn 中使用 react-hooks-testing-library - 不调用 spy

我在设置单元测试以确定使用正确参数调用函数时遇到问题。useAHook返回foo调用 function 的函数bar。代码看起来像这样

//myModule.js
export const useAHook = (arg1, arg2) => {
  const foo = useCallback(() => {
    bar(arg1, arg2);
  }, [arg1, arg2]);

  return foo;
}

export const bar = (a, b) => {
   //does some stuff with a and b
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用renderHookand对这段代码进行单元测试jest.spyOn。我想确认调用函数会foo导致bar使用正确的参数调用。我的单元测试看起来像这样

//myModule.spec.js

import * as myModule from './myModule.js'

it('should call foo with correct arguments', () => {
  const spy = jest.spyOn(myModule, 'bar');
  const { …
Run Code Online (Sandbox Code Playgroud)

jestjs react-hooks-testing-library

4
推荐指数
1
解决办法
5417
查看次数

模拟命名出口用于使用Jest进行测试

我有一个Helper.js具有以下几个辅助功能的文件,该文件正在不同的组件中使用。

    export function buildOptions(elem) { 
        var oList=[];   
        for (var i=0; i < field.length; i++) {
            oList.push (
              <option value={options[i]["id"]}>
                  {options[i][elem]}
              </option>
            )
         }    
         return oList;
      }

      export function B(){
           .....
      }
Run Code Online (Sandbox Code Playgroud)

这是一个利用Helper.js文件中定义的功能的组件。我正在为组件编写测试,我想模拟在此调用的外部函数。

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { buildOptions, A} from './Helper.js';

    class DemoComponent extends React.Component {
        constructor(props) {
            super(props);
        }

        add(e, index) {
            ....
        }


        render() {
            var o_list=buildOptions("name");

            return (
               <div>
                  ...
                  <select required className={selectClass}  >
                      {o_list}
                  </select>  
                  ...           
                  <button …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocking jestjs

3
推荐指数
1
解决办法
5887
查看次数