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



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

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()

但这并没有改变任何事情。对象内部的小丑间谍似乎没有返回其模拟实现

我做错了什么?

mockFn.mockReturnThis((应该可以工作。

例如

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;
},
};

index.test.ts:

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

最新更新