Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jest模拟函数未按预期工作_Javascript_Unit Testing_Jestjs - Fatal编程技术网

Javascript Jest模拟函数未按预期工作

Javascript Jest模拟函数未按预期工作,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我正在尝试为函数createClient创建一个模拟,它应该返回一个特定的对象 但是,由于某些原因,mock被忽略,它运行函数而不是接收mock值 authorization.js authorization.test.js 错误 似乎createClient的模拟没有像我希望的那样工作。它应该返回对象{client:'test'} 您的代码不完整,所以我尝试为您的案例提供一个演示。如果要模拟模块作用域中的私有变量,请使用createClient函数。您可以使用package来实现这一点 例如

我正在尝试为函数createClient创建一个模拟,它应该返回一个特定的对象

但是,由于某些原因,mock被忽略,它运行函数而不是接收mock值

authorization.js

authorization.test.js

错误

似乎createClient的模拟没有像我希望的那样工作。它应该返回对象{client:'test'}


您的代码不完整,所以我尝试为您的案例提供一个演示。如果要模拟模块作用域中的私有变量,请使用createClient函数。您可以使用package来实现这一点

例如

authorization.js

让createClient=req=>{ if!req.user&&req.user.access\u令牌{ 抛出新错误“未授权”; } 函数getUser{ 返回“真实用户”; } 返回{getUser}; }; const getUser=async client=>{ 返回client.getUser; }; module.exports=选项=>{ const client=createClientoptions.req; return=>getUserclient; }; authorization.test.js:

常数重新布线=需要“重新布线”; 描述'61076881',=>{ 它“应该得到用户”,异步=>{ const authorization=重新布线“/授权”; const mClient={getUser:jest.fn.mockReturnValueOnce'fake user'}; const mCreateClient=jest.fn=>mClient; 授权。uuu设置uuu'createClient',mCreateClient; const options={req:{user:{access_token:'123'}}}; const authorizationMiddleware=authorizationoptions; const user=等待授权中间件; expectuser.toEqual“假用户”; expectmCreateClient.toBeCalledWithoptions.req; expectmClient.getUser.toBeCalledTimes1; }; }; 单元测试结果:

通过stackoverflow/61076881/authorization.test.js 7.601s 61076881 ✓ 应该得到用户10毫秒 测试套件:1个通过,共1个 测试:1项通过,共1项 快照:共0个 时间:8.54秒,估计9秒
源代码:

我建议您重构代码。您希望模拟未导出的函数。我认为这不是一个好决定。创建一个正在创建客户端的模块,并在中间件中要求/导入它。比嘲弄变得简单得多。
// some requires here

const createClient = req => {
  if (!(req.user && req.user.access_token)) {
    throw new Error('Not authorized');
  }
  ...
  return { ... }
}

const getUser = async client => { ... }

module.exports = options => {
  ...
  createClient(req) is called here
  ...
}
import authorization from '../../server/middlewares/authorization';

describe('authorization.js', () => {
   it('Should do something', async done => {

    authorization.createClient = jest.fn(() => ({
        client: 'test',
    }));

    // ACT
    const authorizationMiddleware = authorization();
    const result = await authorizationMiddleware(someOptions);

    // ASSERT
    expect(result).toBe('authorized');
    done();
});