Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.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 fn用作对象属性时未定义_Javascript_Typescript_Unit Testing_Testing_Jestjs - Fatal编程技术网

Javascript Jest fn用作对象属性时未定义

Javascript Jest fn用作对象属性时未定义,javascript,typescript,unit-testing,testing,jestjs,Javascript,Typescript,Unit Testing,Testing,Jestjs,我有一个类,我试图模拟一个对象及其属性 intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // need to mock this chain if (response.headersSent) { // to test this path return true } return false } 如果我使用一个普通的对象文本和一些

我有一个类,我试图模拟一个对象及其属性

intercept(context: ExecutionContext) {
  const response = contect.switchToHttp().getResponse() // need to mock this chain

  if (response.headersSent) { // to test this path
    return true
  }

  return false
}
如果我使用一个普通的对象文本和一些匿名函数来“模拟”依赖关系,那么一切都会按预期进行

const executionContext = {
  switchToHttp: () => executionContext, // calls itself to simulate 'this' chaining
  getRequest: () => {
    return {
      url: undefined,
      method: undefined,
      headers: undefined,
      connection: {
        remoteAddress: undefined,
        remotePort: undefined
      }
    }
  },
  getResponse: () => {
    return {
      headersSent: true, // but i want an easy way to change this in tests without using a factory
      append: () => undefined
    }
  }
} as unknown as ExecutionContext

it('test', () => {
  const response = myclass.intercept(executionContext);

  expect(response).toBeTrue()
});
当我尝试使用
jest.fn()模拟某些属性时,我得到了奇怪的结果

const getResponseSpy = jest.fn(() => {
  return {
    headersSent: false,
    append: () => undefined
  }
});

const executionContext = {
  switchToHttp: () => executionContext,
  getRequest: () => {
    return {
      url: undefined,
      method: undefined,
      headers: undefined,
      connection: {
        remoteAddress: undefined,
        remotePort: undefined
      }
    }
  },
  getResponse: getResponseSpy // easier way to change this
} as unknown as ExecutionContext
在我的代码中的这一点上,我得到的响应是
undefined

TypeError: Cannot read property 'headersSent' of undefined
如果我执行类似于
getResponse:()=>getResponseSpy
的操作,那么代码中的
response
是一个Jest模拟对象,而不是模拟实现。这当然缺少
headersSent
属性

我觉得我做错了什么。我试过使用

switchToHttp: jest.fn().mockResturnThis()
但这并没有改变任何事情。对象中的jest spy似乎没有返回其模拟实现

我做错了什么?

应该有用

例如

index.ts

interface ExecutionContext {
  switchToHttp(): ExecutionContext;
  getResponse(): ExecutionContext;
  headersSent: boolean;
}

export const myclass = {
  intercept(context: ExecutionContext) {
    const response = context.switchToHttp().getResponse();

    if (response.headersSent) {
      return true;
    }

    return false;
  },
};
import { myclass } from './';

describe('67837058', () => {
  it('should pass', () => {
    const executionContext = {
      switchToHttp: jest.fn().mockReturnThis(),
      getResponse: jest.fn().mockReturnThis(),
      headersSent: true,
    };
    const response = myclass.intercept(executionContext);
    expect(response).toBeTruthy();
  });
});
index.test.ts

interface ExecutionContext {
  switchToHttp(): ExecutionContext;
  getResponse(): ExecutionContext;
  headersSent: boolean;
}

export const myclass = {
  intercept(context: ExecutionContext) {
    const response = context.switchToHttp().getResponse();

    if (response.headersSent) {
      return true;
    }

    return false;
  },
};
import { myclass } from './';

describe('67837058', () => {
  it('should pass', () => {
    const executionContext = {
      switchToHttp: jest.fn().mockReturnThis(),
      getResponse: jest.fn().mockReturnThis(),
      headersSent: true,
    };
    const response = myclass.intercept(executionContext);
    expect(response).toBeTruthy();
  });
});
测试结果:

 PASS  examples/67837058/index.test.ts (8.387 s)
  67837058
    ✓ should pass (3 ms)

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

我澄清了这个问题,我不认为这是关于锁链