在执行单元测试用例之前,我应该如何获得API令牌?



在我的单元测试用例中,我试图对API中的一些数据进行单元测试,因此需要API令牌。我希望找到一种方法来调用令牌API,并在触发任何API之前将其存储在Redux中。

我知道Jest中的setup.js,尝试在那里调用我的API,并且在Redux中存储不太好用。我不认为setup.js在开始单元测试之前等待方法完全完成。

// Within the Setup.js, I was calling method directly
const getAPItoken = async() => {
await getToken();
}
getAPItoken();

目前,我正在单元测试文件中的1中获得API令牌。方法完成后,其余的单元测试将正常运行,因为它们从Redux获得API令牌。

我现在正在做的示例

describe('Get API token', () => {
test('it should return true after getting token', async () => {
// Within the method itself, it actually store the token to redux upon receiving from API, also it will return TRUE upon success
const retrievedToken = await getToken();
expect(retrievedToken).toBeTruthy();
});

有更好的方法来处理这个问题吗?

您可以使用globalSetup。它接受一个async函数,该函数在所有测试套件之前触发一次。

因此您可以优化API密钥并将其设置在节点global对象上,以便您可以从任何地方访问它。

// setup.js
module.exports = async () => {
global.__API_KEY__ = 'yoru API key';
};
// jest.config.js
module.exports = {
globalSetup: './setup.js',
};

最新更新