【发布时间】:2020-11-17 21:07:37
【问题描述】:
假设有以下嵌套服务类,其中 private 字段 myCache 和公共方法 myFunction:
import * as NodeCache from 'node-cache'
class MyService{
private myCache = new NodeCache();
myFunction() {
let data = this.myCache.get('data');
if(data === undefined){
// get data with an http request and store it in this.myCache with the key 'data'
}
return data;
}
}
我想针对两种不同的情况测试函数 myFunction。 第一种情况:如果条件为真。第二种情况:如果条件为假。
这是缺少两个测试的测试类:
import { Test, TestingModule } from '@nestjs/testing';
import { MyService} from './myService';
describe('MyService', () => {
let service: MyService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [MyService],
}).compile();
service = module.get<MyService>(MyService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('myFunction', () => {
it('should return chached data', () => {
// first test
}),
it('should return new mocked data', () => {
// second test
})
})
});
因此我想我必须访问或模拟 myCache 私有类字段。 因为它是私有的,所以我无法在测试类中访问它。
我的问题是:实现这一目标的最佳和正确方法是什么?
【问题讨论】:
-
私人会员可以通过
service['myCache']访问。可能不需要这样做,而是mock需要mock的数据源,也就是NodeCache。 -
好的,现在我知道如何访问它了,但是我如何才能以正确的方式用 jest 来模拟它呢?
标签: javascript unit-testing mocking jestjs nestjs