/
strategy-adapter.test.ts
72 lines (66 loc) · 2.5 KB
/
strategy-adapter.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright IBM Corp. 2013,2017. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {expect} from '@loopback/testlab';
import {StrategyAdapter, UserProfile} from '../..';
import {ParsedRequest, HttpErrors} from '@loopback/rest';
import {MockStrategy} from './fixtures/mock-strategy';
import * as http from 'http';
describe('Strategy Adapter', () => {
const mockUser: UserProfile = {name: 'user-name', id: 'mock-id'};
describe('authenticate()', () => {
it('calls the authenticate method of the strategy', async () => {
let calledFlag = false;
// TODO: (as suggested by @bajtos) use sinon spy
class Strategy extends MockStrategy {
// override authenticate method to set calledFlag
async authenticate(req: http.ServerRequest) {
calledFlag = true;
await super.authenticate(req);
}
}
const strategy = new Strategy();
const adapter = new StrategyAdapter(strategy);
const request = <ParsedRequest>{};
await adapter.authenticate(request);
expect(calledFlag).to.be.true();
});
it('returns a promise which resolves to an object', async () => {
const strategy = new MockStrategy();
strategy.setMockUser(mockUser);
const adapter = new StrategyAdapter(strategy);
const request = <ParsedRequest>{};
const user: Object = await adapter.authenticate(request);
expect(user).to.be.eql(mockUser);
});
it('throws Unauthorized error when authentication fails', async () => {
const strategy = new MockStrategy();
strategy.setMockUser(mockUser);
const adapter = new StrategyAdapter(strategy);
const request = <ParsedRequest>{};
request.headers = {testState: 'fail'};
let error;
try {
await adapter.authenticate(request);
} catch (err) {
error = err;
}
expect(error).to.be.instanceof(HttpErrors.Unauthorized);
});
it('throws InternalServerError when strategy returns error', async () => {
const strategy = new MockStrategy();
strategy.setMockUser(mockUser);
const adapter = new StrategyAdapter(strategy);
const request = <ParsedRequest>{};
request.headers = {testState: 'error'};
let error;
try {
await adapter.authenticate(request);
} catch (err) {
error = err;
}
expect(error).to.be.instanceof(HttpErrors.InternalServerError);
});
});
});