我正在为 REST 客户端库编写测试,它必须使用 OAuth 交换“登录”服务。为了防止登录我要测试的每个端点,我想编写某种“测试设置”,但我不确定我应该如何执行此操作。
我的测试项目结构:
- 测试
- endpoint-category1.spec.ts
- endpoint-category2.spec.ts
如果我只有一个“端点类别”,我会有这样的东西:
describe('Endpoint category 1', () => {
let api: Client = null;
before(() => {
api = new Client(credentials);
});
it('should successfully login using the test credentials', async () => {
await api.login();
});
it('should return xyz\'s profile', async () => {
const r: Lookup = await api.lookup('xyz');
expect(r).to.be.an('object');
});
});
我的问题:
因为 login() 方法是那里的第一个测试,所以它会起作用,并且客户端实例也可用于所有后续测试。但是,如何进行某种设置,使“已登录的 api 实例”可供我的其他测试文件使用?
最佳答案
公共(public)代码应移至beforeEach
:
beforeEach(async () => {
await api.login();
});
此时 should successfully login using the test credentials
没有多大意义,因为它没有断言任何东西。
关于node.js - Mocha 使用异步初始化代码进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49802445/