【发布时间】:2019-10-26 23:53:30
【问题描述】:
我正在尝试为我的数据库爬虫程序设置测试,但我无法替换我正在测试的类方法导入的内容。
为了不写太多代码,我只列出问题的一般形式。在我的测试功能中,我有:
describe("test",()=>{
let result1;
beforeAll(async ()=>{
await createConnection();
})
afterAll(async ()=>{
getConnection().close();
})
test("setup test",async () => {
result1 = await WeatherController.startForecastAPI();
expect(result1.status).toBe(Status.SUCCESS);
})
})
WeatherController.ts 文件(...其中代码被取出):
...
import AccessTokenService from '../services/AccessTokenService';
export default class WeatherController{
...
static async startForecastAPI(){
...
const accessToken = AccessTokenService.getAccessToken();//get and validate token
...
}
}
在 WeatherController 类中,startForecastAPI 被定义为静态异步方法。该类导入了多个其他类,其中包括用于获取有效访问令牌的 AccessTokenService 类。 AccessTokenService.getAccessToken() 应该返回一个对象,该对象具有通过 http 请求获得的多个属性。
我想模拟调用 AccessTokenService 的结果,但我没有直接在我的测试函数中调用它,我正在调用 WeatherController 而 WeatherController 正在调用 AccessTokenService。如何在测试时替换 WeatherController 调用的内容但不触及 WeatherController 代码?我已经尝试过浏览 jest 文档,但我对这一切都很陌生,而且它们令人困惑。我也不完全清楚范围是如何在这里工作的(我尝试在测试代码中定义一个函数并在测试函数中调用它,但它超出了范围)。
测试函数中的 await WeatherController.startForecastAPI() 调用返回未定义,但是当我将 accessToken 硬编码为有效对象时,代码工作正常,我只是找不到将该对象注入代码的方法测试函数。
【问题讨论】:
标签: javascript testing mocking jestjs